<title>Algorithm – Sort 1</title> Algorithm – Sort 1
Conventions: In code L, and R are closed intervals, for example, there are 10 elements of an array, then L and R in my code are 0 and 9, respectively. (use from small to large sort)
Bubble sort
If there are n elements, then we have to go n-1 times, choose one of the largest, and then throw to the back.
void Bubble(int L,int R) { for(int I= L; I <= r-1; i++) {// n-1 Times for(int J= L; J < R-i; J + +) {// because the values behind the R-i have been lost (ordered) if(A[j] > A[j+1]) {Swap (A, J, j+1);// when you find the big, you start throwing it back.} } }}
Select sort
Unlike bubble sorting, selecting a sort is the first to select the smallest and then start putting it in front. We want to find the smallest value in an array.
int min = a[0];for (int i = 1; i < n; i++) { if (A[i] > min) { min = a[i]; }}
Now we just need to find the lowest value subscript.
int min = 0;for (int i = 1; i < n; i++) { if (A[i] > A[min]) { min = i; }}
Here is the code to select the sort.
void Select_sort (intlintr) {for (inti = l; I <= r-1; ++i) { intmin = i; for (intJ = i+1; J <= R; ++j) { if (A[j] < a[k]) { min = j; } } Swap (A, k, i);} }
Insert Sort
Insert sort It's like when we're playing poker, we touch a card, and we're going to start from the right to the left, (assuming you're holding a stack of cards in your left hand, if you're the right hand, that's the reverse).
First, assuming that the card is of size key and that his subscript is I, then he is going to be from i-1 to 0. J from I-1 to 0. If there is a bigger card than him, push the card backwards, pushing it from J to (J+1). If this card (j) is less than key, then our key card will be placed behind J, that is, j+1 = key.
void Insert_sort (intlintr) {for (inti = l+1; I <= R; i++) { intkey = A[i]; int J = i-1; while (J >= 0 && A[j] > key) { a[j+1] = a[j]; j--; } A[J+1] = key; }}
Date:2015-01-16 15:42:29
Author:sunx
created:2015-01-20 Tue 12:58
Emacs 24.4.2 (ORG mode 8.2.10)
Validate
Algorithm--Sort 1