Wednesday 4 October 2017

Java Code for Insertion Sort

Problem:

Sort the given array using Insertion Sort

Solution:

package com.basics;

import java.util.Arrays;

public class InsertionSort {

public static void main(String[] args) {
int[] array = {31, 41, 59, 26, 41, 58};
doInsertionSort(array);
System.out.println(Arrays.toString(array));
}

public static void doInsertionSort(int[] a){
int key = 0;
int j = 0;
for (int i = 1; i < a.length; i++) {
key = a[i];
j = i-1;
while(j > -1 && a[j] > key){
a[j+1] = a[j];
j = j-1;
}
a[j + 1] = key;

}
}

}


Output:

[26, 31, 41, 41, 58, 59]


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...