• Java Data Structures Tutorial

Sorting Array Elements



To sort an array follow the steps given below.

  • Compare the first two elements of the array

  • If the first element is greater than the second swap them.

  • Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them.

  • Repeat this till the end of the array.

Swapping an array

  • Create a variable (temp), initialize it with 0.

  • Assign 1st number to temp.

  • Assign 2nd number to 1st number.

  • Assign temp to second number.

Example

import java.util.Arrays;
public class SortingArray {
   public static void main(String args[]) {
   
     // String[] myArray = {"JavaFX", "HBase", "OpenCV", "Java", "Hadoop", "Neo4j"};
      int[] myArray = {2014, 2545, 4236, 6521, 1254, 2455, 5756, 66406}; 

      int size = myArray.length;
      for(int i = 0; i<size-1; i++) {
         for (int j = i+1; j<size; j++) {
            if(myArray[i]>(myArray[j])) {            
               int temp = myArray[i];
               myArray[i] = myArray[j];
               myArray[j] = temp;
            } 
         }     
      }
      System.out.println("Sorted array :"+Arrays.toString(myArray));     
   }
}

Output

Sorted array :[1254, 2014, 2455, 2545, 4236, 5756, 6521, 66406]
Advertisements