After Bubble Sort sorting algorithm in previous tutorial, this time i am covering the Selection sort program code in Java with the output.
The selection sort technique is a combination of searching the smallest or largest element and after that sort the elements in ascending or descending order . During each pass, the unsorted element with the smallest or largest value is moved to its proper position in the array. The idea of selection sort is very simple: we repeatedly find the next largest or smallest element in the array and move it to its final position in the sorted array.
The selection sort technique is a combination of searching the smallest or largest element and after that sort the elements in ascending or descending order . During each pass, the unsorted element with the smallest or largest value is moved to its proper position in the array. The idea of selection sort is very simple: we repeatedly find the next largest or smallest element in the array and move it to its final position in the sorted array.
Selection Sort Java Program
public class SelectionSort { public static void main(String args[]) { int[] x = {547, 3, 523, 378, 133, 1714, 14, 23, 310}; System.out.println("Unsorted list: "); display(x); selectionSort(x); System.out.println("Sorted list: "); display(x); } private static void selectionSort(int x[]) { int n = x.length; int i, indx, j, large; large = x[0]; indx = 0; for (i=n-1; i>0; i--) { large = x[0]; indx = 0; for (j=1; j<=i; j++) if (x[j]>large) { large = x[j]; indx = j; } x[indx] = x[i]; x[i] = large; } } private static void display(int x[]) { for (int i=0; i<x.length; i++) System.out.print(x[i] + " "); System.out.println("\n"); } }

0 comments:
Post a Comment