Sorting an array of integers in java

In computer science and mathematics, a sorting algorithm is an algorithm that puts elements of a list in a certain order.
Summaries of popular sorting algorithms
  1. Bubble sort
  2. Insertion sort
  3. Shell sort
  4. Merge sort
  5. Heap sort
  6. Quick sort
  7. Bucket sort
  8. Radix sort
  9. Distribution sort
  10. Shuffle sort
Make a class named whatever you want like as

public class SortNumbers {

  public static void sort(int[] nums) {
     for (int i = 0; i < nums.length; i++) {
      int min = i;
     
      for (int j = i; j < nums.length; j++) {
        if (nums[j] < nums[min])
          min = j;
      }
     
      int tmp;
      tmp = nums[i];
      nums[i] = nums[min];
      nums[min] = tmp;
    }
  }


  public static void main(String[] args) {
    int[] nums = new int[args.length]; // Create an array to hold numbers
    for (int i = 0; i < nums.length; i++)    
      nums[i] = Integer.parseInt(args[i]);

    sort(nums); // Sort them
    for (int i = 0; i < nums.length; i++)
      // Print them out
      System.out.println(nums[i]);
  }
}
Compile it as:

javac SortNumbers.java
java SortNumbers 45 89 21 74 15 -1 25 7
The output will be as:

-1
7
15
21
25
45
74
89

Comments

Popular posts from this blog

ubuntu package installation

Drupal Bootstrap Database

How to fix 500 internal privoxy error