Hi Everyone ,
In Previous post we have discussed about the Selection Sort its program and its time complexity, Today we are going to code insertion sort using array list, This is the most popular and most used Sort in all after mert sort.
So lets see the code.
Implementation of Insertion Sort Using Array
Output:
[10,23,45,5,3,2,]
[10,23,45,5,3,2,]
[10,23,45,5,3,2,]
[5,10,23,45,3,2,]
[3,5,10,23,45,2,]
[2,3,5,10,23,45,]
[2,3,5,10,23,45,]
Time Complexity:- The Time Complexity of Insertion Sort is O(n^2) as there are two loop used.
So Guys hope you all understand the code and if you have any problem just leave comment.
In Next Post , will share the code of Merge Sort.
Thanks for reading
-Noeik
In Previous post we have discussed about the Selection Sort its program and its time complexity, Today we are going to code insertion sort using array list, This is the most popular and most used Sort in all after mert sort.
So lets see the code.
Implementation of Insertion Sort Using Array
/*
@author noeik
*/
public class InsertionSort {
static int[] data = {10,23,45,5,3,2};// global data integer array
public static void main(String[] args) {
sort(data);
}
public static void sort(int[] data)
{
int j;
int current;
for(int i=0;i<data.length;i++)
{
current =data[i];
j=i-1;
while(j>=0&&data[j]>current)
{
data[j+1]=data[j];
j--;
}
data[j+1]=current;
display();
}
}
// displaying the array method
public static void display()
{
String result = "[";
for(int d :data)
{
result = result +d+",";
}
result =result+"]";
System.out.println(result);
}
}
Output:
[10,23,45,5,3,2,]
[10,23,45,5,3,2,]
[10,23,45,5,3,2,]
[5,10,23,45,3,2,]
[3,5,10,23,45,2,]
[2,3,5,10,23,45,]
[2,3,5,10,23,45,]
Time Complexity:- The Time Complexity of Insertion Sort is O(n^2) as there are two loop used.
So Guys hope you all understand the code and if you have any problem just leave comment.
In Next Post , will share the code of Merge Sort.
Thanks for reading
-Noeik
0 comments:
Post a Comment