120 likes | 240 Views
Quadratic performance. Sorting. Selection sort. elements are selected in order and placed in their final sorted positions i th pass selects the i th largest element in the array, and places it in the ( n-i) th position of the array an “interchange sort”; i.e., based on swapping.
E N D
Quadratic performance Sorting
Selection sort • elements are selected in order and placed in their final sorted positions • ith pass selects the ith largest element in the array, and places it in the (n-i)th position of the array • an “interchange sort”; i.e., based on swapping
public static void selectionsort( int[] data, int first, int n) { int i, j; int temp;// used during swap int big; // index of largest value // in data[first…first + i] }
public static void selectionsort( int[] data, int first, int n) { for (i = n-1; i>0; i--) { big = first; for (j=first+1; j<=first+i; j++) if (data[big] < data[j]) big=j; temp = data[first+i]; data[first+i] = data[big]; data[big] = temp; } }
public static void selectionsort( int[] data, int first, int n) { int i, j, temp; int big; // index of largest value // in data[first…first + i] for (i = n-1; i>0; i--) { big = first; for (j=first+1; j<=first+i; j++) if (data[big] < data[j]) big=j; temp = data[first+i]; data[first+i] = data[big]; data[big] = temp; } } Trace…
Analysis of selection sort • best, average, and worst case time • Θ(n2) comparisons, • Θ(n)swaps • Θ(n2)time—quadratic.
Advantages of Selection sort • can be done “in-place”—no need for a second array • minimizes number of swaps
Insertion sort • begin with “sorted” list of one element • sequentially insert new elements into sorted list • size of sorted list increases, size of unsorted list decreases
public static void insertionsort( int[] data, int first, int n) { int i, j; int entry; for (i=1; i<n; i++) { entry = data[first + i]; for (j= first+i; test ; j--) data[j] = data[j-1]; data[j]=entry; } } // test: (j>first)&&(data[j-1]>entry)
Analysis of Insertion sort • worst case: • elements initially in reverse of sorted order. • Θ(n2) comparisons, swaps • average case: • same analysis as worst case • best case: • elements initially in sorted order • no swaps • Θ(n) comparisons
Analysis of Insertion sort (cont’d) Overall, insertion sort requiresO(n2)time
Advantages of Insertion sort • can be done “in-place” • if data is in “nearly sorted” order, runs in Θ(n)time