The basic idea of bubble sorting: (in ascending order, for example) an array of n elements is in principle ordered n-1. For each lying sort, start with the first number and then compare the size of the previous number to the next. If the previous number is larger than the last one, it is exchanged. After such a round, the largest number will appear as the last array element. In the second round, the last number is removed, and the number of the first n-1 is followed by the above steps to find the maximum number, which will be called the second-lowest array element ... after the n-1 round, the sorting was completed. /* Bubble sort Analysis: raw Data: 28, 30, 19, 2, 23 first trip: first time: 28, 30, 19, 2, 23 second time: 28, 19, 30, 2, 23 third time: 28, 19, 2, 30, 23 fourth time: 28, 19, 2, 23, 30 Second Trip: First time:19, 28, 2, 23, 30 Second time: 19,&NBSP;2,&NBSP;28,&NBSP;23,&NBSP;30&NBsp; third time:19, 2, 23, 28, 30 third trip: first time: 2, 19, 23, 28, 30 second time: 2, 19, 23, 28, 30 Fourth Trip: First time:2, 19, 23, 28, 30 */ //n elements comparison n-1 //per trip comparison = array elements - number of times code implementation: //randomly generates an array of 20 elements with a value range of [20, 40] int a[20] = {0}; printf ("a randomly generated array containing 20 elements: \ n"); for (int i = 0; i < 20; i++) { a[i] = Arc4random ()% (40&NBSP;-&NBSP;20&NBSP;+&NBSP;1) + 20; //arc4random generates a random number printf ("%d ", a[i]); } for (int i = 0; i < 20 - 1; i++) { //comparison of the number of trips for (int j = 0; j < 20 - 1 - i; j++) { //of comparison per trip if (A[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } printf ("\ n bubble sort, produces a set of arrays from small to large order: \ n"); for (int i = 0; i < 20; i++) { printf ("%d ", a[ I]); }
This article is from the "You Do not know" blog, please be sure to keep this source http://9217856.blog.51cto.com/9207856/1563522
The bubble sort of the iOS algorithm (iv)