Classic Sort algorithm-bubbling sort bubble sort
The principle is that the proximity of the number 22 is compared, in order from small to large or from large to small,
After such a trip, the largest or smallest number was exchanged to the last one,
And then start from the beginning of the 22 exchange, until the end of the second, the other similar to see examples
Examples for small to large sort,
Original sorted Array | 6 | 2 | 4 | 1 | 5 | 9 |
First Order (outer loop)
First time 22 comparison 6 > 2 Exchange (Inner loop)
Pre-Exchange Status | 6 | 2 | 4 | 1 | 5 | 9 |
Post-Exchange Status | 2 | 6 | 4 | 1 | 5 | 9 |
Second 22 comparison, 6 > 4 Exchange
Pre-Exchange Status | 2 | 6 | 4 | 1 | 5 | 9 |
Post-Exchange Status | 2 | 4 | 6 | 1 | 5 | 9 |
Third time 22 comparison, 6 > 1 Exchange
Pre-Exchange Status | 2 | 4 | 6 | 1 | 5 | 9 |
Post-Exchange Status | 2 | 4 | 1 | 6 | 5 | 9 |
Fourth time 22 comparison, 6 > 5 Exchange
Pre-Exchange Status | 2 | 4 | 1 | 6 | 5 | 9 |
Post-Exchange Status | 2 | 4 | 1 | 5 | 6 | 9 |
Fifth time 22 comparison, 6 < 9 do not exchange
Pre-Exchange Status | 2 | 4 | 1 | 5 | 6 | 9 |
Post-Exchange Status | 2 | 4 | 1 | 5 | 6 | 9 |
Second Order (outer loop)
First time 22 comparison 2 < 4 do not exchange
Pre-Exchange Status | 2 | 4 | 1 | 5 | 6 | 9 |
Post-Exchange Status | 2 | 4 | 1 | 5 | 6 | 9 |
Second 22 comparison, 4 > 1 Exchange
Pre-Exchange Status | 2 | 4 | 1 | 5 | 6 | 9 |
Post-Exchange Status | 2 | 1 | 4 | 5 | 6 | 9 |
Third time 22 comparison, 4 < 5 do not exchange
Pre-Exchange Status | 2 | 1 | 4 | 5 | 6 | 9 |
Post-Exchange Status | 2 | 1 | 4 | 5 | 6 | 9 |
Fourth time 22 comparison, 5 < 6 do not exchange
Pre-Exchange Status | 2 | 1 | 4 | 5 | 6 | 9 |
Post-Exchange Status | 2 | 1 | 4 | 5 | 6 | 9 |
Third Order (outer loop)
First time 22 comparison 2 > 1 exchange
Post-Exchange Status | 2 | 1 | 4 | 5 | 6 | 9 |
Post-Exchange Status | 1 | 2 | 4 | 5 | 6 | 9 |
Second 22 comparison, 2 < 4 do not exchange
Post-Exchange Status | 1 | 2 | 4 | 5 | 6 | 9 |
Post-Exchange Status | 1 | 2 | 4 | 5 | 6 | 9 |
Third time 22 comparison, 4 < 5 do not exchange
Post-Exchange Status | 1 | 2 | 4 | 5 | 6 | 9 |
Post-Exchange Status | 1 | 2 | 4 | 5 | 6 | 9 |
Four-trip sort (outer loop) No Exchange
Five-trip sort (outer loop) No Exchange
Sorting finished, output final result 1 2 4 5 6 9
Code for reference only
static void Bubble_sort (int[] unsorted)
{for
(int i = 0; i < unsorted. Length; i++)
{for
(int j = i; J < unsorted. Length; J + +)
{
if (Unsorted[i] > Unsorted[j])
{
int temp = unsorted[i];
Unsorted[i] = unsorted[j];
UNSORTED[J] = temp;
}}} static void Main (string[] args)
{
int[] x = {6, 2, 4, 1, 5, 9};
Bubble_sort (x);
foreach (var item in x)
{
Console.WriteLine (item);
}
Console.ReadLine ();
}
Bubble Sort Animation Demo
The above is a small set to introduce the classic sorting algorithm of the bubble sort (Bubble sort) code, I hope to help!