import java.util.ArrayList;
import java.util.List;
public class Insertion_sort {
public static void insertion(int[] arr){
int temp;
System.out.println("Before sorting");
for(int a=0; a<arr.length; a++){
System.out.print(" "+arr[a]);
}
for(int i = 1; i<arr.length; i++) {
int value_to_sort = arr[i]; // Consider the second element to sort, since first element is considered to be sorted
int j = i; // have both i and j at second place
while(j>0 && arr[j-1]>value_to_sort){//while j>0 means first place is not reached, we need to continuously move it up the ladder
//arr[j-1]>value_to_sort, if first element is greater than the swap
arr[j] = arr[j-1];
j--;//the number right not be in the right place may be it is required to move further up, so decrement j and check
}
arr[j]= value_to_sort; // finally put the number in its place
}
System.out.println();
System.out.println("After sorting");
for(int a=0; a<arr.length; a++){
System.out.print(" "+arr[a]);
}
}
public static void main(String[] args) {
int[] arr = {10, 7, 1, 2, 4, 5};
insertion(arr);
}
}
import java.util.List;
public class Insertion_sort {
public static void insertion(int[] arr){
int temp;
System.out.println("Before sorting");
for(int a=0; a<arr.length; a++){
System.out.print(" "+arr[a]);
}
for(int i = 1; i<arr.length; i++) {
int value_to_sort = arr[i]; // Consider the second element to sort, since first element is considered to be sorted
int j = i; // have both i and j at second place
while(j>0 && arr[j-1]>value_to_sort){//while j>0 means first place is not reached, we need to continuously move it up the ladder
//arr[j-1]>value_to_sort, if first element is greater than the swap
arr[j] = arr[j-1];
j--;//the number right not be in the right place may be it is required to move further up, so decrement j and check
}
arr[j]= value_to_sort; // finally put the number in its place
}
System.out.println();
System.out.println("After sorting");
for(int a=0; a<arr.length; a++){
System.out.print(" "+arr[a]);
}
}
public static void main(String[] args) {
int[] arr = {10, 7, 1, 2, 4, 5};
insertion(arr);
}
}
No comments:
Post a Comment