Friday 13 October 2017

Java Code for Selection Sort

Problem:

Consider sorting n numbers stored in array A by first finding the smallest element
of A and exchanging it with the element in A[1]. Then find the second smallest
element of A, and exchange it with A[2]. Continue in this manner for the first n-1
elements of A. Write pseudocode for this algorithm, which is known as selection
sort.

Solution:

package com.basics;

import java.util.Arrays;
import java.util.Scanner;

public class SelectionSort {

static int[] array;
int arrayLimit;

public static void main(String[] args) {
SelectionSort selectionSort = new SelectionSort();
selectionSort.initializeTheArrays();
System.out.println("Before sorting an array is " + Arrays.toString(array));
selectionSort.doSelectionSort();
System.out.println("After sorting an array is " + Arrays.toString(array));

}

public void initializeTheArrays(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the array limit");
arrayLimit = scanner.nextInt();
array = new int[arrayLimit];
System.out.println("enter the array elements");
for (int i = 0; i < array.length; i++) {
System.out.println("enter the element");
array[i] = scanner.nextInt();
}
scanner.close();
}

public void doSelectionSort(){
int index ;
for (int i = 0; i < array.length - 1; i++) {
index = i;
for (int j = i + 1; j < array.length; j++) {
if(array[j] < array[index]){
index = j;
}
}

int min = array[index];
array[index] = array[i];
array[i] = min;

}
}

}

Output:

enter the array limit
5
enter the array elements
enter the element
12
enter the element
3
enter the element
44
enter the element
333
enter the element
2
Before sorting an array is [12, 3, 44, 333, 2]
After sorting an array is [2, 3, 12, 44, 333]

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