You are here : Home / Core Java Tutorials / Interview Programs (beginner to advanced) in java / Level1 programs for (beginner)
In this core java programming tutorial we wrote a program to sort string using Selection sort in java.
Example 1 to sort string using Selection sort in java>
Input = java
Output = aajv
Example 2 to sort string using Selection sort in java>
Input = javaMadeSoEasy
Output = vysojedaaaaSME
Program/ example to sort string using Selection sort in java >
/*
* write a program to sort string using Selection sort in java
*/
public class SelectionSortOnString {
static String stringToBeSorted= "java";
//static String stringToBeSorted= "javaMadeSoEasy"; //Test String
static char[] ar = stringToBeSorted.toCharArray();
public static void main(String[] args) {
selectionSort();
System.out.println(ar);
}
public static void selectionSort() {
int outer, inner, minimum;
for (outer = 0; outer < ar.length - 1; outer++) // outer loop
{
minimum = outer;
for (inner = outer + 1; inner < ar.length; inner++)// inner loop
if (ar[inner] < ar[minimum]) // if minimum greater,
minimum = inner; // we have a new minimum
swap(outer, minimum); // swap them
}
}
/*
* This method swaps two elements in Array
*/
private static void swap(int pos1, int pos2) {
char temp = ar[pos1];
ar[pos1] = ar[pos2];
ar[pos2] = temp;
}
}
/*OUTPUT
aajv
*/
|
So in this core java programming tutorial we wrote a program to sort string using Selection sort in java.
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
Related >
Level2 programs
>7) Write a Program to find out Fibonacci series using recursion - example in java - interview programs
>9) How to Remove duplicate elements from sorted array example in java - important interview programs
>11) Write a program to find out substring in given string example in java - important interview programs
Labels:
Core Java