Home Tutorial Java Core Java insertion sort with string array

 
 

Java insertion sort with string array
Posted on: December 10, 2012 at 12:00 AM
In this tutorial, you will learn how to sort array of strings using string array with Insertion Sort.

Java insertion sort with string array

In this tutorial, you will learn how to sort array of strings using string array with Insertion Sort. For this, we have created a method that accepts string array and size and returns the sorted array using inserting sort algorithm. In the main method, we have  invoked the method and pass array of strings to it.

Example:

public class SortStringArrayUsingInsertionSort{

public static void main(String[] args){
String[] arr ={"Atlanta","New York","Dallas","Omaha","San Francisco"};
int count = 0;
String sortedArray[] = sort_sub(arr, arr.length); 
for(int i=0;i<sortedArray.length;i++){
System.out.println(sortedArray[i]);
}
}

public static String[] sort_sub(String array[], int f){
String temp="";
for(int i=0;i<f;i++){
for(int j=i+1;j<f;j++){
if(array[i].compareToIgnoreCase(array[j])>0){
temp = array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
return array;
}
}

Output:

Atlanta
Dallas
New York
Omaha
San Francisco

Related Tags for Java insertion sort with string array:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.