O(n^2) Sortings
Insertion Sort:
Time Complexity: Best O(n) (when already sorted); Average O(n^2); Worst O(n^2).
Space Complexity: O(1)
public static void main(String[] args) { int[] a = new int[]{3,2,9,0,1,7,5,4,8,6}; insertionSort(a); System.out.println(Arrays.toString(a)); } public static void insertionSort(int[] a) { for(int i = 1;i<a.length;++i) { int j = i; while(j>=1 && a[j]<a[j-1]) { int temp = a[j]; a[j] = a[j-1]; a[j-1] = temp; --j; } } }
♠ Improvement:
If comparsion incurs much more cost than swap(e.g. if the element is an object, not an integer), we can do binary search for the sorted array while doing insertion. With this we can improve this algorithm to O(nlogn) for comparison but still O(n^2) for swaps.
Bubble Sort:
Time Complexity: Best O(n) (when already sorted); Average O(n^2); Worst O(n^2).
Space Complexity: O(1)
public static void main(String[] args) { Random r = new Random(); int[] a = new int[]{r.nextInt(100),r.nextInt(100),r.nextInt(100),r.nextInt(100),r.nextInt(100),r.nextInt(100),r.nextInt(100),r.nextInt(100),r.nextInt(100)}; int[] aCopy1 = Arrays.copyOf(a, a.length); int[] aCopy2 = Arrays.copyOf(a, a.length); bubbleSort(aCopy1); optimizedBubbleSort(aCopy2); System.out.println(Arrays.toString(a)); System.out.println(Arrays.toString(aCopy1)); System.out.println(Arrays.toString(aCopy2)); } public static void bubbleSort(int[] a) { int end = a.length; boolean swapped = true; while(swapped) { swapped = false; for(int i = 1;i<end;++i) { if(a[i]<a[i-1]) { int temp = a[i]; a[i]=a[i-1]; a[i-1]=temp; swapped = true; } } --end; } } public static void optimizedBubbleSort(int[] a) { int end = a.length; while(end>0) { int newEnd = 0; for(int i = 1;i<end;++i) { if(a[i]<a[i-1]) { int temp = a[i]; a[i]=a[i-1]; a[i-1]=temp; newEnd = i; } } end = newEnd; } }
Selection Sort:
Time Complexity: Best O(n^2); Average O(n^2); Worst O(n^2).
Space Complexity: O(1)
public static void main(String[] args) { Random r = new Random(); int[] a = new int[]{r.nextInt(100),r.nextInt(100),r.nextInt(100),r.nextInt(100),r.nextInt(100),r.nextInt(100),r.nextInt(100),r.nextInt(100),r.nextInt(100)}; int[] aCopy1 = Arrays.copyOf(a, a.length); int[] aCopy2 = Arrays.copyOf(a, a.length); selectionSort(aCopy1); System.out.println(Arrays.toString(a)); System.out.println(Arrays.toString(aCopy1)); } private static void selectionSort(int[] a) { for(int i = 0;i<a.length-1;++i) { int minIndex = i; for(int j = i+1;j<a.length;++j) { if(a[j]<a[minIndex]) minIndex = j; } if(minIndex != i) { int temp = a[i]; a[i] = a[minIndex]; a[minIndex] = temp; } } }

浙公网安备 33010602011771号