Tech Rocks

Coldfusion
Java
JQuery

An online resource for latest web technologies like Coldfusion, JRun, Pro*C, JQuery, HTML5, PHP, W3C, Java, J2EE, C, C++, ORACLE, PL/SQL, MySql, Ajax, Coldbox, Fusebox, UNIX, JavaScript, NodeJS and much more...

Wednesday, February 26, 2014

Selection sort in java

The  first iteration will give the smallest number at the first end of the list. The elements starting from the first is compared / swapped with the rest of the positions.

N-1 iterations for N items. Time complexity is O(n2)

public class MySelectionSort {

public static int[] doSelectionSort(int[] arr){

for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;

int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}

public static void main(String a[]){

int[] arr1 = {10,34,2,56,7,67,88,42};
int[] arr2 = doSelectionSort(arr1);
for(int i:arr2){
System.out.print(i);
System.out.print(", ");
}
}
}


Output will be like



2, 7, 10, 34, 42, 56, 67, 88, 

0 comments :