1. bubble sort

1.1. The initial version

1 void bubble_sort_1(int *arr,int length) {
2     int i, j;
3     for (i = 0; i < length; i++) {
4         for (j = 0; j < length-i-1; j++) {
5             if (arr[j] > arr[j + 1])
6                 std::swap(arr[j], arr[j + 1]);
7         }
8     }
9 }

1.2 Improved 1: If during the cycle to a certain step, I found the overall has been ordered, the direct end of the cycle.

 1 void bubble_sort_2(int a[], int n) {
 2      for (bool sorted = false; sorted = !sorted; n--) {
 3          for (int i = 1; i != n; i++) {
 4              if(a[i - 1]> a[i]){
 5              std::swap(a[i - 1], a[i]);
 6              sorted = false;
 7             }
 8          }
 9      }
10  }

1.3 Improvement 2: recording each reverse rightmost point (point of the latter half has been ordered), the reordering may be performed from that point to the left, some of the steps have been omitted in order reordering.

 1 void bubble_sort_3(int a[], int n) {
 2     int last = 0;
 3     int a_border = n;
 4     for (bool sorted = false; sorted = !sorted; a_border--) {
 5         for (int i = 1; i != a_border; i++) {
 6             if (a[i - 1] > a[i]) {
 7                 std::swap(a[i - 1], a[i]);
 8                 sorted = false;
 9                 last = i;
10             }
11         }
12         a_border = last;
13     }
14 }

 

Guess you like

Origin www.cnblogs.com/Royzzzzz/p/11070008.html