Insertion sort

1. Definition

    The complexity of insertion sort is O(n*n), and its improved algorithm is Hill sort, so it is necessary to understand insertion sort before understanding Hill sort.

    Algorithm idea: Suppose there are n unordered numbers, let i=1; j=i; in the first pass, we first use the variable tem to save the number of position i, and then compare the position j and

    The size of tem (the default is ascending order) if the number of tem is greater than the number at position j, the number at position j-1 is directly assigned to position j, and then the tem is stored.

    The value of the put is assigned to j-1, and the position 0 and position 1 are in order at the end of the first pass. Then i++ (that is, the second inner loop is 2 times), the second pass starts from

    Starting from position 2, comparing position 1, position 2 and position 0, a total of n-1 times are required.

! It should be noted here that the number of inner loops in bubble sort and selection sort is getting smaller and smaller, while insertion sort

The number of inner loops of the method increases linearly.

2. Use

    

    Requirements: Input 10 strings to sort them, and output the sorted results.

void Insertion_Sort()
{
	int i = 0,j=0;
 	char array[10][10];
 	char tem[10];
 	printf("please input ten strings\n");//Prompt for input string 
 	for(i=0;i< 10;i++)
 	{
 		scanf("%s",array[i]);//Enter the input string into the array 
 	}
 	for(i=1;i<10;i++)//The main body of the insertion sort algorithm 
 	{
 		strcpy(tem, array[i]);
 		for(j=i;j>0;j--)
 		{
 			if(strcmp(array[j-1],tem))
 			{
 				strcpy(array[j],array[j-1]) ; }
 strcpy(array[j-1],tem); } }
 for(i=0;i<10;i++)
 {
 printf("%s ",array[i]); }	
								
			
						
		
}
intmain()
{
	Insertion_Sort();	

    

Welcome to point out the shortcomings






Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326587830&siteId=291194637