In the interview occasionally will be asked to sort the algorithm, and sometimes will be asked to write the sorting algorithm, but has not been a thing. Until the day before the interview was asked to write a program on the spot to sort the given array. At that time originally wanted to write a bubble sorting algorithm, wrote to the last found to write a nondescript sort program, bubbling does not bubble, insert does not insert, come back after thinking is need to study some of these sorting algorithm, so decided to these several commonly used sorting algorithm summed up.
Sorting requirements : Array A of length n is sorted in order from small to large.
Bubble Sort Idea : Given an array of length n, Loop n-1 times, find the maximum number of a[0] to a[n-i-1] in each loop, and place that number in a[n-1].
How do I find out the maximum number of a[0] to a[n-i-1]? : Loop over, compare a[i] and a[i+1] size, such as a[i]<a[i+1], two number of interchange positions, and then continue to determine the size of a[i+1] and a[i+2] to this loop end.
Example of sorting:
Original array: 2, 0, 3, 6, 8, 4, 9, 5, 1, 7,
1th Round results: 0, 2, 3, 6, 4, 8, 5, 1, 7, 9,
2nd round results: 0, 2, 3, 4, 6, 5, 1, 7, 8, 9,
3rd round results: 0, 2, 3, 4, 5, 1, 6, 7, 8, 9,
4th round results: 0, 2, 3, 4, 1, 5, 6, 7, 8, 9,
5th round results: 0, 2, 3, 1, 4, 5, 6, 7, 8, 9,
6th round results: 0, 2, 1, 3, 4, 5, 6, 7, 8, 9,
7th round results: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
8th Round results: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
9th round Results: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
Public void mybubblesort (int[] array) { for (int i = 0; i < array.length-1; i++) { for (int j = 0; J < array.length-i-1; j + +) {if (Array[j] > array[j + 1]) { int num = array[j]; = Array[j + 1]; + 1] = num; }}} }
Note the range of two cycles:
Number of outer loops: n-1 times, fixed, even before N-m (0<m<n) has finished sorting ( note 7.8.9 Cycles in the sort example ), the program still loops n-m to n-1.
Number of internal cycles: according to the change of outer circulation, the number of times is (n-i-1) +......+2++1
Sort-bubble sort