applying insertion sort on string in java code example
Example 1: applying insertion sort on string in java
public static void insertion(String[] ans){ //Main Methord
for (int i = 0; i < ans.length-1; i++) {
for (int j = i + 1; j > 0; j--) {
if (ans[j].compareTo(ans[j - 1]) < 0) {
String temp = ans[j];
ans[j] = ans[j - 1];
ans[j - 1] = temp;
}
}
}
}
public static void main(String[] args){ //driver code
String[] ans = {"xa","ax"};
insertion(ans);
}
Example 2: Insertion sort string array java
// Insertion sort string array java
public class InsertionSortString
{
public static void main(String[] args)
{
String[] arrFruits = {"Orange","Mango","Apple","Pineapple","Banana"};
String[] strSorted = sortStringArray(arrFruits, arrFruits.length);
for(int a = 0; a < strSorted.length; a++)
{
System.out.println(strSorted[a]);
}
}
public static String[] sortStringArray(String[] strArray, int g)
{
String temp = "";
for(int a = 0; a < g; a++)
{
for(int b = a + 1; b < g; b++)
{
if(strArray[a].compareToIgnoreCase(strArray[b]) > 0)
{
temp = strArray[a];
strArray[a] = strArray[b];
strArray[b] = temp;
}
}
}
return strArray;
}
}