-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathSelectionSort.java
51 lines (41 loc) · 1.33 KB
/
SelectionSort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package demos;
import java.util.Scanner;
public class SelectionSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);//user input using scanner
System.out.println("Enter the size of the array");//taking size of the array from user
int size=sc.nextInt();
int array[]=new int[size];//declaring array of n elements to be sorted
System.out.println("Enter"+ size + "elements to sort");
for(int i=0;i<size;i++)//taking array elements from user and storing them in array
{
array[i]=sc.nextInt();
}
System.out.println("Array before sort");
for(int i=0;i<size;i++)//taking array elements from user and storing them in array
{
System.out.print(array[i]+ " ");//Printing elements of array before sorting in a single line
}
SelectionSorting(array);
}
public static void SelectionSorting(int array[]){
for(int i=0;i<array.length;i++)
{
for(int j=i+1;j<array.length;j++)
{
if(array[i]>array[j])//if i'th element of array is greater than j'th element swap the elements
{
int temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
System.out.println("Array after sorting");
for(int i=0;i<array.length;i++)
{
System.out.print(array[i]+ " ");//Printing elements of array after sorting in a single line
}
}
}