/* ArrayExp.java -- Array example program
by Craig Persiko for CS 111A
Inputs a series of numbers into an array, sorts them,
and outputs them.
*/
import java.util.Scanner;
class ArrayExp
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] nums; // array reference variable
int idx, numEntries, idxSmall;
System.out.print("How many numbers do you want to enter? ");
numEntries = scan.nextInt();
// allocate the array, now that we know its size:
nums = new int[numEntries];
System.out.println("Enter your numbers (integers), separated by spaces or returns:");
for (idx = 0; idx < numEntries; idx++)
{
nums[idx] = scan.nextInt();
}
// 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$ java ArrayExp
How many numbers do you want to enter? 5
Enter your numbers (integers), separated by spaces or returns:
1 2 5 0 7
In sorted order, the numbers you entered are:
0, 1, 2, 5, 7
-bash-3.2$ java ArrayExp
How many numbers do you want to enter? 6
Enter your numbers (integers), separated by spaces or returns:
3 8 1
6 -6 23
In sorted order, the numbers you entered are:
-6, 1, 3, 6, 8, 23
-bash-3.2$ java ArrayExp
How many numbers do you want to enter? 3
Enter your numbers (integers), separated by spaces or returns:
6 82 13 1
In sorted order, the numbers you entered are:
6, 13, 82
*/
syntax highlighted by Code2HTML, v. 0.9