Problem:
Sort an array into descending order.
Solution:
package array.programs;
import java.util.Scanner;
public class SelectionSortForDescendingOrder {
int[] array;
int limit;
public static void main(String[] args) {
SelectionSortForDescendingOrder selectionSort = new SelectionSortForDescendingOrder();
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
8
enter the element
20
enter the element
35
enter the element
18
enter the element
8
enter the element
14
enter the element
41
enter the element
3
enter the element
39
41 39 35 20 18 14 8 3
Sort an array into descending order.
Solution:
package array.programs;
import java.util.Scanner;
public class SelectionSortForDescendingOrder {
int[] array;
int limit;
public static void main(String[] args) {
SelectionSortForDescendingOrder selectionSort = new SelectionSortForDescendingOrder();
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
8
enter the element
20
enter the element
35
enter the element
18
enter the element
8
enter the element
14
enter the element
41
enter the element
3
enter the element
39
41 39 35 20 18 14 8 3
No comments:
Post a Comment