Question 1. Please be detailed. Will Rate Insertion Sort: An Example (CLRS) 4 6
ID: 3869986 • Letter: Q
Question
Question 1. Please be detailed. Will Rate
Explanation / Answer
nsertion sort : Insertion is good for small elements only because it requires more time for sorting large number of elements. In insertion sort sort array by checking one element to other if next element is bigger then previous just swap them this is the main logic of insertion sort. In following program you can understand better.
public class InsertionSorting {
public static void main(String a[]){
int[] unsortedArray = {19,45,34,22,67,47,77};
insertionSort(unsortedArray);
}
public static void insertionSort(int[] values) {
int temp;
for(int i=0;i<values.length;i++) { //Outer loop
for(int j=i;j>0;j--) { //inner loop
if(values[j]<values[j-1]) {
temp=values[j];
values[j]=values[j-1];
values[j-1]=temp;
}
}
}
System.out.println("insertion sort : "+Arrays.toString(values));
}
}
Explanation :
int[] arr = {19,45,34,22,67,47,77};
pos= 0, 1, 2, 3, 4, 5, 6
when i=0
start loop arr[i] value is 19
j=0 but j>0 not true so again inner loop will not run go to outer loop i++
when i=1
j=1 and also j>0 true
check arr[j] <arr[j-1] mean arr[1] < arr[0] means 45<19 false
j-- check j>0 not true so again inner loop will not run go to outer loop i++
when i=2
j=i mean j=2 and also j>0 true
check arr[j] > arr[j-1] mean arr[2] < arr[1] means 34<45 true
swap value now arr will be
{19,34,45,22,67,47,77};
j-- then j=1;
check arr[j] > arr[j-1] mean arr[1] < arr[0] means 34<19 false
j-- j=0 j>0 false again outer loop will run i++
Now for i reach 3
Same above thing will repeat till i=5 because condition is i<arr.length
then arr will be {19, 22 ,34 , 45 ,47 ,67 ,77};
If you have any query please comment :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.