Sorting an Array

When you have grouped a bunch of similar items together into an array, one of the things you can do easily is rearrange items. The following statements switch the values of two elements in an integer array called numbers:

int temp = numbers[5];
numbers[5] = numbers[6];
numbers[6] = temp;

These statements result in numbers[5] and numbers[6] trading values with each other. The integer variable called temp is used as a temporary storage place for one of the values being swapped.

The most common reason to rearrange elements of an array is to sort them into a specific order. Sorting is the process of arranging a list of related items into a set order. An example would be sorting a list of numbers from lowest to highest.

Santa Claus, ...

Get SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.