Results 1 to 2 of 2
Thread: how to sort
- 11-20-2007, 04:29 AM #1
Member
- Join Date
- Nov 2007
- Posts
- 13
- Rep Power
- 0
- 11-20-2007, 06:56 AM #2
Sorting Strings
String implements the Comparable interface so we can use the compareTo method for sorting. See first paragraph and "Classes Implementing Comparable" table at Object Ordering for bird's–eye view.
Java Code:public class Sorting { public static void main(String[] args) { String[] array = { "five", "Apple", "Zebra", "Key", "elements" }; sort(array); print(array); sortIgnoreCase(array); print(array); } private static void sort(String[] strs) { for(int j = 0; j < strs.length; j++) { String minValue = strs[j]; int minIndex = j; for(int k = j+1; k < strs.length; k++) { if(strs[k].compareTo(minValue) < 1) { minValue = strs[k]; minIndex = k; } } if(minIndex != j) { // found a lower value - swap elements String temp = strs[j]; strs[j] = minValue; strs[minIndex] = temp; } } } private static void sortIgnoreCase(String[] strs) { for(int j = 0; j < strs.length; j++) { String minValue = strs[j].toLowerCase(); int minIndex = j; for(int k = j+1; k < strs.length; k++) { if(strs[k].toLowerCase().compareTo(minValue) < 1) { minValue = strs[k].toLowerCase(); minIndex = k; } } if(minIndex != j) { // found a lower value - swap elements String temp = strs[j]; strs[j] = minValue; strs[minIndex] = temp; } } } private static void print(String[] strs) { for(int j = 0; j < strs.length; j++) { System.out.print(strs[j]); if(j < strs.length-1) System.out.print(", "); } System.out.println(); } }
Similar Threads
-
How to sort a list using Bubble sort algorithm
By Java Tip in forum AlgorithmsReplies: 3Last Post: 04-29-2008, 08:04 PM -
need help with bubble sort
By lowpro in forum New To JavaReplies: 3Last Post: 12-17-2007, 05:27 PM -
sort
By Camden in forum New To JavaReplies: 7Last Post: 11-28-2007, 01:11 AM -
Heap Sort
By kesav2005 in forum Advanced JavaReplies: 1Last Post: 11-13-2007, 11:40 AM -
how to sort 2 tables
By valery in forum AWT / SwingReplies: 1Last Post: 08-06-2007, 08:30 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks