Exchange Selection Sort in Java

A class Sorter contains an array of n integers. Some of the member functions of the Sorter class are given below:

Class name: Sorter
Data members:
n: to store the number of integers
a[]: an array of n integers
Member functions:
Sorter(): constructor
void input(): to input n integers.
void display(): to display the list of integers.
int minimum(int, int): returns the index of the smallest integer in the array between the start index and the last index in the unsorted array.
void sort(): sorts the array in ascending order using exchange selection sort technique and display the sorted array using the display() function.

Specify the class Sorter, giving details of the constructor, input(), display(), minimum(), sort(). You do not need to write the main() function.

Program:

import java.io.*;
class Sorter{
    private int n;
    private int a[];
    public Sorter(){
        n = 0;
    }
    public void input()throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("N = ");
        n = Integer.parseInt(br.readLine());
        a = new int[n];
    }
    public void display(){
        for(int i = 0; i < n; i++)
            System.out.print(a[i] + "\t");
        System.out.println();
    }
    public int minimum(int start, int end){
        int small = a[start];
        for(int i = start + 1; i <= end; i++){ 
            if(small > a[i])
                small = a[i];
        }
        return small;
    }
    public void sort(){
        for(int i = 0; i < n; i++){
            int small = a[i];
            int pos = i;
            for(int j = i + 1; j < n; j++){ 
                if(small > a[j]){
                    small = a[j];
                    pos = j;
                }
            }
            int temp = a[i];
            a[i] = a[pos];
            a[pos] = temp;
        }
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.