1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
/* Java Sort char Array Example This example shows how to sort a char array using sort method of Arrays class of java.util package. */ import java.util.Arrays; public class SortCharArrayExample { public static void main(String[] args) { //create char array char[] c1 = new char[]{'d','a','f','k','e'}; //print original char array System.out.print("Original Array :t "); for(int index=0; index < c1.length ; index++) System.out.print(" " + c1[index]); /* To sort java char array use Arrays.sort() method of java.util package. Sort method sorts char array in ascending order and based on quicksort algorithm. There are two static sort methods available in java.util.Arrays class to sort a char array. */ //To sort full array use sort(char[] c) method. Arrays.sort(c1); //print sorted char array System.out.print("nSorted char array :t "); for(int index=0; index < c1.length ; index++) System.out.print(" " + c1[index]); /* To sort partial char array use sort(char[] c, int startIndex, int endIndex) method where startIndex is inclusive and endIndex is exclusive */ char[] c2 = new char[]{'d','a','f','k','e'}; Arrays.sort(c2,1,4); //print sorted char array System.out.print("nPartially Sorted char array :t "); for(int index=0; index < c2.length ; index++) System.out.print(" " + c2[index]); } } /* Output Would be Original Array : d a f k e Sorted char array : a d e f k Partially Sorted char array : d a f k e */ |
why is originial array and partially sorted array the same after you initialise Arrays.sort(c2,1,4); @line 44..
public static void stringSort(String string){
/* String to character array */
char[] charArray = string.toCharArray();
/* Iterate through the array */
for (int i = 0; i < string.length – 1; i++){
for (int j = i + 1; j < string.length; j++){
int st = Character.toLowerCase(charArray[i])
– Character.toLowerCase(charArray[j]);
/* Case insensitive comparison */
if ( st == 0 )
/* letters are the same */
st = charArray[i] – charArray[j];
/* Case sensitive comparison */
if (st > 0){
int temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
}
}
}