Insert sort (C language), insert sort C Language
Enter a number and insert it to the sorted queue.
1. Define an sorted integer Array
For example:
int arry[7]={2,3,5,11,15,17};
Or enter a string of integer arrays and then sort them (both bubble and select)
The following uses the Bubble sorting method:
# Include <stdio. h> int main () {int I, j, min = 0, num [7]; for (I = 0; I <6; I ++) {printf ("Enter the number of % d", I + 1); scanf ("% d", & num [I]) ;}for (j = 0; j <6; j ++) {for (I = 0; I <6; I ++) {if (num [I]> num [I + 1]) {min = num [I + 1]; num [I + 1] = num [I]; num [I] = min ;}} for (I = 0; I <6; I ++) {printf ("% d", num [I]);}
Return 0 ;}
2. Enter a number num1;
Code:
Int num1; printf ("Please input one as number:"); scanf ("% d", & num1 );
Third: locate the insert position of the input number (locate the subscript index)
In three cases
① Num1 is greater than the previous number, and smaller than the next number
② Num1 is smaller than the minimum number
③ Num1 is greater than the maximum number
Int I = 0; int index = 0; for (I; I <6; I ++) // locate the index subscript position {if (num1> = num [I] & num1 <= num [I + 1]) {index = I + 1; break;} if (num1 <num [0]) {index = 0; break;} if (num1> num [5]) {index = 6; break ;}}
Fourth: Find the subscript (insert position), The number between the start of the insert position and the end of the array, and the next one is equal to the previous value (implement the move assignment process)
For (I = 6; I> index; I --) // move {num [I] = num [I-1];} num [index] = num1; // locate the subscript assignment
Fifth: Output array num
for(i=0;i<7;i++) { printf("%d,",num[i]); }
The overall code is as follows:
# Include <stdio. h> int main (void) {int num [7] = {2, 3, 5, 11, 15, 17}, num1; printf ("Please input one as the number :"); scanf ("% d", & num1); int I = 0; int index = 0; for (I; I <6; I ++) // locate the index subscript position {if (num1> = num [I] & num1 <= num [I + 1]) {index = I + 1; break;} if (num1 <num [0]) {index = 0; break;} if (num1> num [5]) {index = 6; break ;}} for (I = 6; I> index; I --) // move {num [I] = num [I-1];} num [index] = num1; // find the subscript value for (I = 0; I <7; I ++) {printf ("% d,", num [I]) ;}}