selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort.
Selection sort is noted for its simplicity, and it has performance
advantages over more complicated algorithms in certain situations,
particularly where auxiliary memory is limited.
The algorithm divides the input list into two parts: the sub-list of
items already sorted, which is built up from left to right at the front
(left) of the list, and the sub-list of items remaining to be sorted that
occupy the rest of the list. Initially, the sorted sub-list is empty and
the unsorted sub-list is the entire input list. The algorithm proceeds
by finding the smallest (or largest, depending on sorting order) element
in the unsorted sub-list, exchanging (swapping) it with the leftmost
unsorted element (putting it in sorted order), and moving the sub-list
boundaries one element to the right.
Algorithm
Algorithm
The selection sort algorithm is performed using following steps...
- Step 1: Select the first element of the list (i.e., Element at first position in the list).
- Step 2: Compare the selected element with all other elements in the list.
- Step 3: For every comparison, if any element is smaller than selected element (for Ascending order), then these two are swapped.
- Step 4: Repeat the same procedure with next position in the list till the entire list is sorted.
Program
import java.util.Scanner;
public class SelnSort
{
public static void main(String args[])
{
int size, i, j, temp;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Array Size : ");
size = sc.nextInt();
int arr[] = new int[size];
System.out.print("Enter Array Elements : ");
for(i=0; i<size; i++)
{
arr[i] = scan.nextInt();
}
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.print(" Array after Sorting is :\n");
for(i=0; i<size; i++)
{
System.out.print(arr[i]+ " ");
}
}
}
public class SelnSort
{
public static void main(String args[])
{
int size, i, j, temp;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Array Size : ");
size = sc.nextInt();
int arr[] = new int[size];
System.out.print("Enter Array Elements : ");
for(i=0; i<size; i++)
{
arr[i] = scan.nextInt();
}
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.print(" Array after Sorting is :\n");
for(i=0; i<size; i++)
{
System.out.print(arr[i]+ " ");
}
}
}
No comments:
Post a Comment