I wrote this program for sorting an array of type String
alphabetical without using compareTo()
method so I am saying that if you can find errors in my program please tell me I will try to fix it.
class some{
public static void main(String[] args) {
String array[]={"names here"};
System.out.print("before:");
for (int i=0 ;i<array.length;i++ )
System.out.print(array[i]+" ");
array = SortA(array);
System.out.println();
System.out.print("after:");
for (int i=0 ;i<array.length;i++ )
System.out.print(array[i]+" ");
}//end of main method
public static int getSmallestRange(String[] array){
int range = array[0].length()-1;
for (int i =0;i<array.length ;i++ ) {
if(range>array[i].length()-1){
range = array[i].length()-1;
}
}
return range ;
}
public static String[] SortA(String [] array){
String tmp="";
int index = 0 ;
for (int i =0;i<array.length ;i++ )
for (int j = i+1;j<array.length ;j++ ) {
if(array[i].charAt(index)>array[j].charAt(index)){
tmp = array[i];
array[i] = array[j];
array[j] = tmp ;
}//end of if
}//end of loop
index++;
for (int x =0;x<array.length-1 ;x++ ){
for (int y =x+1;y<array.length ;y++ ) {
if(array[x].charAt(0)==array[y].charAt(0)){
if(array[x].charAt(index)>array[y].charAt(index)){
tmp = array[x];
array[x] = array[y];
array[y] = tmp ;
}
else if(array[x].charAt(index)==array[y].charAt(index)){
if(index<getSmallestRange(array))
index++;
}
}//end of if
}//end of loop
}
return array;
}//end of method
}
1 Answer 1
First off, your use of whitespace is a mess, fix it. Press "Format Code" in your favorite IDE or do it manually.
class some{
- The Java Naming Conventions say that class names should be UpperCamelCase.
- Use a visibility modificator for clearness (
private
,public
).
String array[]={"names here"};
Use descriptive variable names, like sourceArray
or unsortedArray
.
for (int i=0 ;i<array.length;i++ )
- Use appropriate variable names. This is a little bit unpopular with most people, but I prefer to use descriptive names even for such simple loops (
int idx
). As said before, your use pf whitespace is very confusing:
for (int idx = 0; idx < array.length; idx++) {
Use appropriate loops, in this case a
for-each
loop:for (String item : array) {
String tmp="";
int index = 0 ;
Declaring variables once and reusing them through out whole function, especially larger functions, is bad. Declare variables where you need them and name them appropriately, like this:
String swapTemp = array[i];
array[i] = array[j];
array[j] = swapTemp;
}//end of if
}//end of loop
If code is correctly formatted, short and precise (only do one function per function), such comments are absolutely unnecessary.
Consider using the Java Documentation feature.
{"dds", "dda"}
, it fails to sort them properly. \$\endgroup\$