Bubble sort is the most common way of sorting small data, the following is implemented in C language, and its two optimization methods.
The first optimization method is to set a marker bit to mark whether an interchange has occurred, and to end prematurely if no exchange occurs;
The second optimization method is to record the location of the final release swap, as the next trip to the end of the position.
#include <stdio.h>/* * Print array * */void printArray (int arr[], int n) {int i = 0;for (i = 0; i < n; ++i) {printf ("%d ", Arr[i]);} printf ("\ n");} /* * Bubble Sort * */void bubblesort (int arr[], int n) {int i = 0;int j = 0;int tmp = 0;for (i = 0; i < n; ++i) {for (j = 0; j < n-1-I; ++J) {if (Arr[j] < Arr[j + 1]) {tmp = Arr[j];arr[j] = arr[j + 1];arr[j + 1] = tmp;}}}} /* * Bubble Sort optimization * Set a flag to flag a trip whether the interchange occurred * If no interchange occurs, the array is already ordered * */void bubbleSort1 (int arr[], int n) {int i = 0;int j = 0;int tmp = 0;int flag = 0; for (i = 0; i < n; ++i) {flag = 0;for (j = 0; J < n-1-I; ++j) {if (Arr[j] < Arr[j + 1]) {flag = 1;tmp = Arr[j ];ARR[J] = arr[j + 1];arr[j + 1] = tmp;}} if (flag = = 0) {break;}}} /* * Bubble sort Optimization Two * Use a variable to record the last occurrence of the swap position, after which no exchange has been ordered * so you can use this value as the next comparison end position * */void bubbleSort2 (int arr[], int n) {int i = 0 ; int j = 0;int k = 0;int tmp = 0;int flag = n; for (i = 0; i < flag; ++i) {k = Flag;flag = 0;for (j = 0; j < K; ++j) {if (Arr[j] < Arr[j + 1]) {flag = J;tmp = A RR[J]; Arr[j] = arr[j + 1];arr[j + 1] = tmp;}}} int main () {int arr[] = {9, 5, 8, 4, 7, 3, 2, 0, 6, 1};p Rintarray (arr), BubbleSort2 (arr.);p Rintarray (arr.); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Bubble sorting and two optimization methods