Home Tutorial Java Core Java insertion sort with string array

 
 

Share on Google+Share on Google+
Java insertion sort with string array
Posted on: December 10, 2012 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Java insertion sort with string array:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 10, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com