Download presentation
Presentation is loading. Please wait.
Published byMaryann Spencer Modified over 8 years ago
1
Sorting Slowly
2
Swap (used in bubble sort and selectSort) public static void swap(int[] array, int a, int b ) { //save a int temp = array[a]; //copy b to a array[a] = array[b]; //copy a to b array[b] = temp; }
3
Bubble Sort (Naive version) public static void bubbleSort(int[] array, int n) { for (int loop=0; loop < n-1; loop++) for (int i = 1; i < n-loop; i++) { if (a[i] < a[i-1]) swap(array, i, i-1) } }
4
insert public static void insert(int x, int[] sorted, int n) { while (n > 0 && x < sorted[n-1]) {//shift until find insertion point sorted [n] = sorted[n-1]; } sorted [n] = x; }
5
insertionSort public static void insertionSort(int[] a, int n) { for (int k = 0; k < n; k++) {//repeatedly insert in place insert(a[k], a, k); } }
6
findMax public static int findMax(int[] array, int n) { int indexMax = 0; for (int k = 1; k array[indexMax]) indexMax = k; //index of largest element return indexMax; }
7
selectSort public static void selectSort (int[] array, int n) { for (int k = n; k > 1; k--) { //repeat until sorted //select largest unsorted value int select = findMax(array, k); //move to end swap(array, select, k-1); } }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.