Summarize and analyze three simple sorting methods (bubble, selection, quick) and binary search:
1. Sorting method
algorithm | Bubble Sort | selection sort | quick sort |
time complexity | On²) | On²) | O(n log n ) |
The basic idea of Bubble Sort is to compare two adjacent numbers in turn, placing the decimals in the front and the large numbers in the back.
void BubbleSort(int *a,int n ) { for(int i = 0;i<n-1;i++) { for(int j = 0;j<n-1-i;j++) { if(a[j]>a[j+1]) { int t = a[j]; a[j] = a[j+1]; a[j+1] = t; } } } }
The basic idea of selection sort: find the smallest one from the sequence to be sorted each time, and put it at the end of the sorted sequence.
void SelectionSort(int *a,int n ) { for(int i = 0;i<n-1;i++) { for(int j = i + 1;j<n;j++) { if(a[i]>a[j]) { int t = a[j]; a[j] = a[i]; a[i] = t; } } } }
The basic idea of quick sort is to divide the data to be sorted into two independent parts by one-pass sorting, and all the data in one part is smaller than all the data in the other part, and then perform quick sorting on these two parts (recursive call).
void qsort(int *a,int start,int end) { if(start >= end) return; //stop recursion int i = start; int j = end; int key = a[i]; //reference bit while(i<j) { while(i<j&&a[j]>=key) { j--; } a[i] = a[j]; while(i<j&&a[i]<=key) { i++; } a[j] = a[i]; } a [i] = key; // Someone a [j] = key; qsort(a,start,i-1); //Recursive call to quickly sort the left and right sides qsort(a,i+1,end); }
Depending on the time complexity, Bubble & Selection Sort works well for small lists and Quick Sort works on large lists .
In general, selection sort is better than bubble sort (about 7 times more efficient).
However, if the array is completely ordered, the inner bubbling loop will not be executed once (it can detect whether the entire array is already in order), and the selection sort has to be exchanged with itself once every time, so the bubbling efficiency is high. (this is very rare)
Two, binary search
string search(int a[],int num) { int low = 0; int high = sizeof(a)-1; while(low <= high) { int mid = (low + high)/2; int guess = a[mid]; if(guess == num ) { return "found"; } if(guess > num) { high = mid - 1; }else{ low = mid +1; } } return "Not found"; }
Time complexity O(log n)
Note: The list of elements found must be ordered