18 views

## Problem:

I am struggling with a problem for a few hours back. I know how to sort an array by using methods. I was looking for another way (perhaps a loop) to do it more efficiently. Let me put my question this way, how to sort an array in java without using sort method? Could anybody here please help to make this happen?

| 18 views

+1 vote

## Solution:

To mitigate the method you can use the iteration process to sort an array. This program takes a little more time time to execute. Moreover, this algorithm is not so efficient. So, my advice would be, use a sort function to sorting an array.

As per your question, I am trying to giving you a possible solution below:

``````public class ArraySort {
public static void main(String[] args) {

int [] array = new int [] {5, 2, 8, 7, 1};
int tem = 0;

for (int n = 0; n < array.length; n++) {
for (int m = n+1; m < array.length; m++) {
if(arr[n] > array[m]) {
tem = array[n];
array[n] = array[m];
array[m] = tem;
}
}
}

System.out.println();

System.out.println("Elements of array sorted in ascending order: ");
for (int n = 0; n < array.length; n++) {
System.out.print(array[n] + " ");
}
}
}    ``````

Here I used a temporary variable named tem to make an empty space and sorting my elements.

The above program will sort your array in ascending order and provide an output:

``````Elements of array sorted in ascending order:
1 2 5 7 8 ``````

Thanks

by (56.2k points)
edited

Many predefined functions make your work easier but sometimes we want to do without using them.

# Procedure:

To sort the array without using the sort algorithm, take the array of strings and sort the array based on the first string. Once you have done, then take the array of strings again and sort it based on the second character. Then again based on the third character and so on until you reach the length of the largest string.

## Example:

This example will sort array elements in ascending and descending order both without using array sort method;

``````int a[]={6,2,5,1};
System.out.println(Arrays.toString(a));

int temp;
for(int i=0;i<a.length-1;i++){

for(int j=0;j<a.length-1;j++){

if(a[j] > a[j+1]){   // use < for Descending order

temp = a[j+1];

a[j+1] = a[j];

a[j]=temp;

}

}

}

System.out.println(Arrays.toString(a));``````

### Output:

`````` [6, 2, 5, 1]    // output for ascending order

[1, 2, 5, 6]  //output for descending order``````

## Second Example:

In this example we sort the array by using bubble sort.

``````public static void main(String[] args) {

int[] arr = new int[] { 6, 8, 7, 4, 312, 78, 54, 9, 12, 100, 89, 74 };
for (int i = 0; i < arr.length; i++) {

for (int j = i + 1; j < arr.length; j++) {

int tmp = 0;

if (arr[i] > arr[j]) {

tmp = arr[i];

arr[i] = arr[j];

arr[j] = tmp;

}

}

}

}``````

by (2.8k points)