Skip to content

Instantly share code, notes, and snippets.

@MichelePipi
Created July 25, 2021 02:57
Show Gist options
  • Save MichelePipi/71ae8afd0a20ed849b4162c8c5566010 to your computer and use it in GitHub Desktop.
Save MichelePipi/71ae8afd0a20ed849b4162c8c5566010 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
// write your code here
int[] nums = new int[]{801, 7317, 3946, 240, 9935, 4293, 7260, 3414, 1533, 786, 6297, 3946, 4355, 2535, 4919};
sort(nums);
System.out.println(findDuplicateNumber(nums));
}
private static int findDuplicateNumber(int[] nums) {
long time = System.nanoTime();
long end;
nums = sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i + 1]) {
end = System.nanoTime();
System.out.println("Found duplicate in " + (end - time) + " nanoseconds");
return nums[i];
}
;
}
end = System.nanoTime();
System.out.println("There was not a duplicate! Found in " + (end - time) + " nanoseconds");
return -1; // No duplicate
}
private static boolean sorted(final int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] > nums[i + 1]) return false;
}
return true;
}
private static int[] sort(final int[] nums) {
long time = System.nanoTime();
boolean sorted = false;
if (sorted(nums)) return nums;
while (!sorted) {
sorted = sorted(nums);
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] > nums[i + 1]) {
int temp = nums[i];
int tempB = nums[i + 1];
nums[i] = tempB;
nums[i + 1] = temp;
}
}
}
long endTime = System.nanoTime() - time;
System.out.println("Sorted in " + endTime + " nanoseconds");
return nums;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment