How to sort array by single for loop in java

Please see below example to sort number types of arrays by using single for loop. The code should be self-explanatory.

Example Code:

import java.util.Arrays;

public class SortArray {

public static void main(String[] args) {

int[] intArray = new int[] { 67, 6, 7,88, 1, 6,7,3, 2, 4, 5, 11, 22 };

System.out.println(“**************int Array before sorting************”);

for (int i : intArray) {

System.out.println(i);

}

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

if(intArray[i]<intArray[i-1]) {

int temp = intArray[i-1];

intArray[i-1] = intArray[i];

intArray[i] = temp;

i=0;

}

}

System.out.println(“**************int Array after sorting************”);

for (int i : intArray) {

System.out.println(i);

}

}

}

Response:

**************int Array before sorting************

67

6

7

88

1

6

7

3

2

4

5

11

22

**************int Array after sorting************

1

2

3

4

5

6

6

7

7

11

22

67

88

Leave a Reply

Your email address will not be published. Required fields are marked *