Problem:
Given a randomly ordered set of n integers, sort them into non-descending order using the selection sort.
Solution:
package array.programs;
import java.util.Scanner;
public class SelectionSort {
int[] array;
int limit;
public static void main(String[] args) {
SelectionSort selectionSort = new SelectionSort();
selectionSort.initilizeTheArray();
selectionSort.doSelectionSort();
selectionSort.printTheArray();
}
public void initilizeTheArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the first array elements limit");
limit = scanner.nextInt();
array = new int[limit];
for (int i = 0; i < array.length; i++) {
System.out.println("enter the element");
array[i] = scanner.nextInt();
}
scanner.close();
}
public void doSelectionSort(){
int position = 0;
int temp = 0;
for (int i = 0; i < array.length - 1; i++) {
position = i;
for (int j = i + 1; j < array.length; j++) {
if(array[position] > array[j]){
position = j;
}
}
temp = array[position];
array[position] = array[i];
array[i] = temp;
}
}
public void printTheArray(){
for (int i = 0; i < array.length; i++) {
System.out.print( array[i] + " ");
}
}
}
Output:
enter the first array elements limit
10
enter the element
23
enter the element
455
enter the element
65
enter the element
43
enter the element
1
enter the element
3
enter the element
456
enter the element
778
enter the element
98
enter the element
66
1 3 23 43 65 66 98 455 456 778
Given a randomly ordered set of n integers, sort them into non-descending order using the selection sort.
Solution:
package array.programs;
import java.util.Scanner;
public class SelectionSort {
int[] array;
int limit;
public static void main(String[] args) {
SelectionSort selectionSort = new SelectionSort();
selectionSort.initilizeTheArray();
selectionSort.doSelectionSort();
selectionSort.printTheArray();
}
public void initilizeTheArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the first array elements limit");
limit = scanner.nextInt();
array = new int[limit];
for (int i = 0; i < array.length; i++) {
System.out.println("enter the element");
array[i] = scanner.nextInt();
}
scanner.close();
}
public void doSelectionSort(){
int position = 0;
int temp = 0;
for (int i = 0; i < array.length - 1; i++) {
position = i;
for (int j = i + 1; j < array.length; j++) {
if(array[position] > array[j]){
position = j;
}
}
temp = array[position];
array[position] = array[i];
array[i] = temp;
}
}
public void printTheArray(){
for (int i = 0; i < array.length; i++) {
System.out.print( array[i] + " ");
}
}
}
Output:
enter the first array elements limit
10
enter the element
23
enter the element
455
enter the element
65
enter the element
43
enter the element
1
enter the element
3
enter the element
456
enter the element
778
enter the element
98
enter the element
66
1 3 23 43 65 66 98 455 456 778
No comments:
Post a Comment