how to sort an simple array logically (for both string & int) ?
without using Arrays.sort(arr) or any comparators.
Here is a nice selection including code examples for the various ways to sort arrays and/or collections: Rosetta Code
Use Arrays.sort()
. See the API documentation of class java.util.Arrays
.
Example:
import java.util.Arrays;
// ...
String[] arr = new String[] { "one", "two", "three" };
Arrays.sort(arr);
edit - Ok, you've edited your question and added "without using Arrays.sort()
". Is this homework? Are you supposed to implement your own sorting algorithm? Then just do some research on sorting algorithms and implement one yourself.
Write a quicksort or mergesort algorithm. Smells homework, too.
I write my own sorting algorithms in my personal projects without looking at any formal sorting algorithms. It keeps my programming edges sharpend, plus it's interesting to see what you can come up with on your own, compared to the more formal sorting algorithms.
To add a little bit more to their answers above - as you mentioned "sorting logically", you can implement your own Comparator and use Arrays.sort(array, comparator).
Is there a specific reason you want to avoid Arrays.sort()
?
I have covered sorting algorithms in Java which includes the bubble sort, quick sort and merge sort with comprehensive code and explanations. You may find the code here.
Have a look at Insertion Sort.
Comparator
, it could be used in a custom, flexible sorting algorithm. Otherwise you need an individual sorting algorithms for each and every data type. Doesn't make much sense.