Skip to content

Instantly share code, notes, and snippets.

@rishi93
Created November 3, 2015 09:52
Show Gist options
  • Save rishi93/3d1255e2db5abb64a267 to your computer and use it in GitHub Desktop.
Save rishi93/3d1255e2db5abb64a267 to your computer and use it in GitHub Desktop.
Selection Sort in Java
import java.io.*;
class Ideone
{
static void printArray(int[] arr)
{
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]);
System.out.print(" ");
}
System.out.println();
}
static void swapElements(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static int[] selectionsort(int[] arr)
{
for(int i = 0; i < arr.length; i++)
{
int min_index = i;
for(int j = i+1; j < arr.length; j++)
{
if(arr[j] < arr[min_index])
min_index = j;
}
swapElements(arr,i,min_index);
}
return arr;
}
public static void main (String[] args)
{
int[] arr = {9,3,2,5,1,6,4,8,7};
printArray(selectionsort(arr));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment