Problem:
Java code to sort an array by using insertion sort
Solution:
package array.programs;
public class InsertionSort {
public static void main(String []args) {
int[] arr1 = {11,35,21,56,7,67,88,42};
int[] arr2 = doInsertionSort(arr1);
for(int i:arr2){
System.out.print(i);
System.out.print(", ");
}
}
public static int[] doInsertionSort(int[] input){
int temp;
for (int i = 1; i < input.length; i++) {
for(int j = i ; j > 0 ; j--){
if(input[j] < input[j-1]){
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
}
return input;
}
}
Output:
7, 11, 21, 35, 42, 56, 67, 88,
Java code to sort an array by using insertion sort
Solution:
package array.programs;
public class InsertionSort {
public static void main(String []args) {
int[] arr1 = {11,35,21,56,7,67,88,42};
int[] arr2 = doInsertionSort(arr1);
for(int i:arr2){
System.out.print(i);
System.out.print(", ");
}
}
public static int[] doInsertionSort(int[] input){
int temp;
for (int i = 1; i < input.length; i++) {
for(int j = i ; j > 0 ; j--){
if(input[j] < input[j-1]){
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
}
return input;
}
}
Output:
7, 11, 21, 35, 42, 56, 67, 88,
No comments:
Post a Comment