Created
November 3, 2015 09:52
-
-
Save rishi93/3d1255e2db5abb64a267 to your computer and use it in GitHub Desktop.
Selection Sort in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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