Insertion sort algorithm
INSERTION-SORT(A)
for i = 1 to n
key ← A [i]
j ← i – 1
while j > = 0 and A[j] > key
A[j+1] ← A[j]
j ← j – 1
End while
A[j+1] ← key
End for
Insertion sort algorithm
INSERTION-SORT(A)
for i = 1 to n
key ← A [i]
j ← i – 1
while j > = 0 and A[j] > key
A[j+1] ← A[j]
j ← j – 1
End while
A[j+1] ← key
End for
insertion sorting
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class InsertionSorting {
public static Scanner scanner = new Scanner(System.in);
public static void main(String[] argh){
int[] arrNotSorted = newArrInitilizer();
enterValues(arrNotSorted);
sortArray(arrNotSorted);
print(arrNotSorted);
}
//Print Array
public static void print(int[] arr){
System.out.print(Arrays.toString(arr));
}
/* looping from "i"(the incremented index in) ==> function
public static int[] sortArray(int [] unsortedArr)
first we initilize an integer "value"= Array[from])
this will be assigned later to the Array in the minmum value index
and while (from > 0) && (Array[from-1] > value)
we assign every next value to the previous one
eventually we decrement ("from")
*/
public static void insertionSorting(int [] toBesorted, int from){
int value = toBesorted[from];
while(from > 0 && toBesorted[from-1] > value){
toBesorted[from] = toBesorted[from-1];
--from;
}
toBesorted[from] = value;
}
/* Looping from index = 1, array with size one concidered sorted)
later "From" will be assigned to i in the function above */
public static int[] sortArray(int [] unsortedArr){
for(int i = 1 ; i < unsortedArr.length ; ++i){
insertionSorting(unsortedArr,i);
}
return unsortedArr;
}
public static int[] newArrInitilizer() {
System.out.println("Enter Array Size .");
int arrSize = scanner.nextInt();
int[] arr = new int[arrSize];
return arr;
}
public static int [] enterValues(int[] arr){
System.out.println("Array being initlized randomly with "+arr.length+" values.");
for(int i = 0 ; i< arr.length ; ++i){
arr[i] = (int) (Math.random()*10);
}
return arr;
}
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us