Wednesday 4 October 2017

Java Code to sort an array into nonincreasing order using Insertion Sort

Problem:

Java Code to sort an array into nonincreasing order 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;
int tmp = 0;
while(j > -1 && a[j] < key){
tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
j = j-1;
}


}
}

}


Output:

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

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...