// Java program for implementation of Selection Sort
class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first
// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
// Prints the array
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver code to test above
public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int arr[] = {64,25,12,22,11};
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}
/* This code is contributed by Rajat Mishra*/
// Java Selection Sort
// -------------------
/*
Time Complexity
Best Time Complexity:O(n^2)
Average Time Complexity:O(n^2)
Worst Time Complexity:O(n^2)
Space Complexity
No auxiliary space is required in Linear Search implementation.
Hence space complexity is:O(1)
*/
import java.util.*;
public class SelectionSort {
public static int[] sort(int arr[]) {
for (int i = 0; i < arr.length; i++) {
int k = i; // referring to current index
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[k]) {
k = j;
}
}
int temp;
//Swapping algorithm
temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
return arr; // returns the sorted array
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[] = new int[10];
System.out.println("Enter Array Values: ");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
int a[] = new int[arr.length];
a = Arrays.copyOf(sort(arr), arr.length); // copies the sorted array to another array
//sorted in ascending order
System.out.println("Sorted Array:");
for (int i = 0; i < a.length; i++) {
System.out.print(+a[i] + " ");
}
}
}