/* SortCommandLine.java -- Array example program
   by Craig Persiko for CS 111A

   Reads from command line a series of numbers into an array, sorts them,
   and outputs them.
*/

import java.util.Scanner;

class SortCommandLine
{
  public static void main(String[] args)
  {
    Scanner scan = new Scanner(System.in);
    int[] nums;  // array reference variable
    int idx, numEntries, idxSmall;
    
    // Make sure user entered at least one command line argument:
    if(args == null || args.length < 1)
    {
      System.out.println("usage: java SortCommandLine 5 4 2 8\nTo sort numbers 5, 4, 2 and 8");
      return;
    }
    numEntries = args.length;
    nums = new int[numEntries];
    // convert command line into integers, and put into nums array.
    for(int i=0; i < numEntries; i++)
      nums[i] = Integer.parseInt(args[i]);

    // now nums array is filled with numbers from command line, and the rest of this program
    // is the same as ArrayExp.java

    // now sort the array using Selection Sort:
    for(int i = 0; i < numEntries - 1; i++)
    {
      idxSmall = indexOfSmallest(nums, i, numEntries-1);
      // make sure we didn't get -1 above.
      // in fact, no need to swap if idx == i either
      // (and idxSmall can't be < i since we use i above)
      if(idxSmall > i)
        swapValues(nums, idxSmall, i);
    }

    // output the array:
    System.out.println("In sorted order, the numbers you entered are:");

    System.out.print(nums[0]); // output first value
    // output rest of array with commas:
    for (idx = 1; idx < numEntries; idx++)
      System.out.print(", " + nums[idx]);
    System.out.println();
  }

  // return the index of the smallest int in the array a
  // between startIndex and endIndex (inclusive).
  // return -1 if there are no elements in the array after startIndex.
  private static int indexOfSmallest(int[] a, int startIndex, int endIndex)
  {
    if(a == null || a.length <= startIndex)
      return -1;

    int indexOfMin = startIndex; // initialize min so we can compare and find smallest value.

    for (int i = startIndex + 1; i <= endIndex; i++)
    {
      if(a[i] < a[indexOfMin])  // if we find a smaller number than the min
        indexOfMin = i;         // then this is the new min.
    }

    return indexOfMin;
  }

  // Exchange a[p1] and a[p2].  Because we can't pass an int by reference,
  // we must pass the array into the function to make the changes stick.
  private static void swapValues(int[] a, int p1, int p2)
  {
      int temp = a[p1];
      a[p1] = a[p2];
      a[p2] = temp;
  }
}

/*  Sample Output:

-bash-3.2$ javac SortCommandLine.java
-bash-3.2$ java SortCommandLine
usage: java SortCommandLine 5 4 2 8
To sort numbers 5, 4, 2 and 8
-bash-3.2$ java SortCommandLine 5 1 4 0 8 6
In sorted order, the numbers you entered are:
0, 1, 4, 5, 6, 8
-bash-3.2$ 

*/


syntax highlighted by Code2HTML, v. 0.9