TechArena Community What is the use of insertion sort in data structure?

#1
04-01-2011
 Member Join Date: Dec 2010 Posts: 12
What is the use of insertion sort in data structure?

I am not able to get the topic insertion sort in data structure. This topic is quite similar to the sorting. This is what I am finding it. I don?t know whether my observation is true or not? I want to know the method used in insertion sort in data structure. If anybody knowing anything or having the solution to this question then please let me know. I am eagerly waiting for the reply as I am very keen in knowing the solution.
#2
04-01-2011
 Member Join Date: May 2009 Posts: 525
Re: What is the use of insertion sort in data structure?

Insertion sort is implemented by inserting a particular element at the appropriate position. In this method the first iteration starts with comparison of 1st element with the 0th element. In the second iteration 2nd element is compared with the 0th and 1st element .In general every iteration an element is compared with all elements before it. During comparison if it is found that the element in question can be inserted at a suitable position then space is created for it by shifting the other element at the suitable position. This procedure is repeated for all elements in the array.
#3
04-01-2011
 Member Join Date: May 2009 Posts: 532
Re: What is the use of insertion sort in data structure?

The insertion sort is also a type of sorting where it starts the comparison of element with the 0th element. It also stores and declares the array which is also done in the other sorting methods.

Code:
```   Declare array AA
store elements in to array AA
set i=0
Repeat till i= 0 to i<=length of array-1                        // for passess
Repeat for j=0 to j<i                    // for comparision
check  if AA[j] >AA[i]             // for exchanging largest number
int  k = AA[j]
AA[j]=AA[i]
set h =i
Repeat till  h>j
arr[h] = arr[h - 1] ;
arr[h+ 1] = k ;
decrement h by 1
end of loop
repeat step 6 to 14
End of loop
increment i by 1
repeat step  5 to 18
end of loop```
#4
04-01-2011
 Member Join Date: May 2009 Posts: 620
Re: What is the use of insertion sort in data structure?

Code:
```  #include <stdio.h>
#include <conio.h>

void main( )
{
int arr[5] = { 25, 17, 31, 13, 2 } ;
int i, j, k, temp ;
clrscr( ) ;
printf ( "Insertion sort.\n" ) ;
printf ( "\nArray before sorting:\n") ;
for ( i = 0 ; i <= 4 ; i++ )
printf ( "%d\t", arr[i] ) ;

for ( i = 1 ; i <= 4 ; i++ )
{

for ( j = 0 ; j < i ; j++ )
{
if ( arr[j] > arr[i] )
{
temp = arr[j] ;
arr[j] = arr[i] ;
for ( k = i ; k > j ; k-- )
arr[k] = arr[k - 1] ;
arr[k + 1] = temp ;
}
}
}
printf ( "\n\nArray after sorting:\n") ;
for ( i = 0 ; i <= 4 ; i++ )
printf ( "%d\t", arr[i] ) ;
}```

 Tags: