Selection Sort Sda
Selection Sort Sda
algos;
The selection sort is a combination of searching and sorting. During each pass, the
unsorted element with the smallest (or largest) value is moved to its proper position in
the array. The number of times the sort passes through the array is one less than the
number of items in the array. In the selection sort, the inner loop finds the next
smallest (or largest) value and the outer loop places that value into its proper location.
Selection sort is not difficult to analyze compared to other sorting algorithms since
none of the loops depend on the data in the array. Selecting the lowest element
requires scanning all n elements (this takesn 1 comparisons) and then swapping it
into the first position. Finding the next lowest element requires scanning the
remaining n 1 elements and so on, for (n 1) + (n 2) + ... + 2 + 1 = n(n 1) / 2
(n2) comparisons. Each of these scans requires one swap for n 1 elements.
1 package com.java2novice.algos;
4
public static int[] doSelectionSort(int[] arr){
5
6
for (int i = 0; i < arr.length - 1; i++)
7
{
8
int index = i;
9
for (int j = i + 1; j < arr.length; j++)
10 if (arr[j] < arr[index])
11 index = j;
12
14 arr[index] = arr[i];
15 arr[i] = smallerNumber;
}
16
return arr;
17
}
18
19
public static void main(String a[]){
20
21
int[] arr1 = {10,34,2,56,7,67,88,42};
22 int[] arr2 = doSelectionSort(arr1);
23 for(int i:arr2){
24 System.out.print(i);
25 System.out.print(", ");
26 }
}
27
}
28
29
30
Output: