Sorting, that is, to organize the data with certain rules, the key to the ranking algorithm is to compare the exchange of data and the number of moves.
Sorting algorithms need to consider: number of data exchange, number of moves, data out of bounds, the practicability of the algorithm (in line with many types)
//Predictive: Use the C # extension method for data output, using StringBuilder to save memory overhead Public Static classdebugextension { Public Static voidDebugarray<t>(t[] array) {StringBuilder SB=NewStringBuilder (Array. Count () *2); for(inti =0; I < array. Count (); i++) {sb. Append (Array[i]); Sb. Append (","); } Console.WriteLine (SB); } }
The following sorting algorithm rules are sorted from left to right, from small to large:
First, insert sort
- Insert sort first consider the data size between the first two elements of the array data[0] and data[1], if data[0] > data[1], then exchange;
- Then consider the next one data[2], after the first sort, data[0] and data[1] is already ordered, then data[2] only need to be compared with the left Data[1], whether the order is reversed, need to exchange, if need to exchange, then data[2] <= > Data[1], when the data in data[1] is compared to the data on the left Data[0] to be exchanged, and so on;
- Each iteration process, the data that needs to be sorted data[j] all the data on the left is already ordered data, just like playing poker, the data[j] each time the data needs to be sorted to the left to fit the position I, need from I to j-1 this ordered data need to move to the right one bit, Then the saved tamp data is inserted into the data[i];
- Iterate from the second number of the array until the last n is inserted into the sorted data on the left, sorting is done
- The code is as follows:
Public voidInsertionsort<t> (t[] datas)whereT:icomparable<t> { for(inti =0; I < datas. Count ()-1; i++) { inttemp; for(intj = i; J >=0; j--) { if(Datas[j] > datas[j +1]) {temp= Datas[j +1]; Datas[j+1] =Datas[j]; DATAS[J]=temp; } } } }
Code Listing 2: Public voidInsertionsort<t> (t[] datas)whereT:icomparable<t> { if(Datas = =NULL)return; //The first round compares N-1 times, from the second number to the last number, and each time in turn is compared to the left for(inti =1, J; I < datas. Count (); i++) {T temp=Datas[i]; for(j = i; j >0&& Temp.compareto (Datas[j-1]) <0; j--) {Datas[j]= Datas[j-1]; } Datas[j]=temp; } }
The array to be sorted is as follows: int 5 7 3 5 2 One - 4 2 1 3 }; new program (); Program. Insertionsort (Insertdatas); Debugextension.debugarray (Insertdatas);
- Result output:
Sorting algorithm Series insertion sort (1)