The common sort algorithm--c# program implements bubble sort
Sorting (sort) is an important operation in computer programming, and it is also a frequently encountered problem in daily life. For example, words in a dictionary are arranged in alphabetical order, otherwise, it is very difficult to use them. Similarly, the order of the data stored in the computer is of great significance for the speed and simplicity of the algorithm that processes the data.
1. Basic Concepts
Sorting is a sequence that rearranges a record (a data element called a record in a sort order) or a sequence that is incremented (or decremented) by the value of one of the recorded data items.
2 Bubble sort (Bubble sort)
Bubble sort is a simple sort algorithm. It repeatedly visits the sequence to sort, compares two elements at a time, and swaps them if they are in the wrong order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted. The algorithm is named because the smaller elements will slowly "float" through the switch to the top of the sequence.
2.1 Algorithm Description
- Compares the adjacent elements. If the first one is larger than the second, swap them two;
- For each pair of adjacent elements to do the same work, from the beginning of the first pair to the end of the last pair, so that the final element should be the largest number;
- Repeat the above steps for all elements except the last one;
- Repeat steps until the sort is complete.
2.2 Dynamic Diagram Demo
2.3c# code for bubbling sort bubble sort
1 /// <summary>2 ///01 Bubble Sort3 /// </summary>4 /// <param name= "Arry" >an array of integers to sort</param>5 Public Static int[] Bubblesort (int[] arry)6 {7 for(inti =0; I < Arry. Length; i++)8 {9 for(intj =0; J < Arry. Length-1I J + +)Ten { One //compares adjacent two elements if the previous one is larger than the next, then swaps the position A if(Arry[j] > arry[j +1]) - { - inttemp = Arry[j +1]; theArry[j +1] =Arry[j]; -ARRY[J] =temp; - } - } + } - returnArry; +}
Print array
1 /// <summary>2 ///Print Array3 /// </summary>4 /// <param name= "Array" ></param>5 Private Static voidPrintArray (int[] array)6 {7 if(Array = =NULL|| Array. Length <=0)8 {9 return;Ten } One for(inti =0; I < array. Length; i++) A { -Console.Write ("["+array[i]+"]"+","); - } the}
Test code:
1 int[] Arraytest =New int[] {1,3,2,5,4,7,6,9,8 };2 3Console.WriteLine ("------------The original array--------------");4 PrintArray (arraytest);5 //Bubble Sort6Console.WriteLine ("\ n------------bubble sort--------------");7PrintArray (Bubblesort (arraytest));
Operation Result:
The common sort algorithm--c# program implements bubble sort