> 14. Selection Sort in Java (for integers)
Arrays in Java: (Part 9)
One Dimensional Array Selection Sort:
14. Selection Sort in Java (for integers)
15. Selection Sort in Java (for Strings)
- Example: Selection Sort in Java (for Integers)
- Example: Selection Sort in Java (for Strings)
This file contains 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.util.Scanner; | |
class selection { | |
public static void main(String []args) { | |
Scanner scan = new Scanner(System.in); | |
System.out.println("number of elements: "); | |
int n = scan.nextInt(); | |
int array[] = new int[n]; | |
System.out.println("Enter " + n + "elements"); | |
for (int i=0; i<n; i++){ | |
array[i] = scan.nextInt(); | |
} | |
for (int i = 0; i < n-1; i++) | |
{ | |
// find the minimum element in unsorted array | |
int min_index = i; | |
for (int j = i+1; j < n; j++){ | |
if (array[j]<array[min_index]) | |
min_index = j; | |
} | |
// swap the found minimum element with the first element | |
int temp = array[min_index]; | |
array[min_index] = array[i]; | |
array[i] = temp; | |
} | |
System.out.println("\nsorted array: "); | |
for (int i=0; i<n;i++) { | |
System.out.println(array[i]); | |
} | |
} | |
} |
This file contains 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.util.Scanner; | |
class selection { | |
public static void main(String []args) { | |
Scanner scan = new Scanner(System.in); | |
System.out.println("number of elements: "); | |
int n = scan.nextInt(); | |
String array[] = new String[n]; | |
System.out.println("Enter " + n + "elements"); | |
for (int i=0; i<n; i++){ | |
array[i] = scan.next(); | |
} | |
for (int i = 0; i < n-1; i++) | |
{ | |
// find the minimum element in unsorted array | |
int min_index = i; | |
for (int j = i+1; j < n; j++){ | |
if (array[j].compareToIgnoreCase(array[min_index])<0) | |
min_index = j; | |
} | |
// swap the found minimum element with the first element | |
String temp = array[min_index]; | |
array[min_index] = array[i]; | |
array[i] = temp; | |
} | |
System.out.println("\nsorted array: "); | |
for (int i=0; i<n;i++) { | |
System.out.println(array[i]); | |
} | |
} | |
} |
Comments
Post a Comment