Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ArraySort {
- //sort an integer array from smallest to largest
- public static void main(String[] args) {
- int[] numbers = new int[10];
- fillArray(numbers);
- System.out.print("Starting numbers: ");
- arrayPrint(numbers);
- sort(numbers);
- System.out.print("Ending numbers: ");
- arrayPrint(numbers);
- }
- //fill an integer array with random numbers
- public static void fillArray(int[] array) {
- int i;
- for( i = 0; i < array.length; i++) {
- array[i] = (int)(Math.random() * 100);
- }
- }
- //print the contents of an array
- public static void arrayPrint(int[] array) {
- int i;
- for(i = 0; i < array.length; i++) {
- System.out.printf("%2d, ", array[i]);
- }
- System.out.print("\n");
- }
- /*
- * sort an integer array
- * depends on swapElement and isSorted
- */
- public static void sort(int[] array) {
- int i;
- while(!isSorted(array)) {
- for(i = 0; i < array.length - 1; i++) {
- if(array[i + 1] < array[i]) swapElement(array, i, i + 1);
- }
- }
- }
- //swaps the elements at the given indices
- public static void swapElement(int[] array, int idxa, int idxb) {
- int temp = array[idxa];
- array[idxa] = array[idxb];
- array[idxb] = temp;
- }
- //test if array is sorted
- public static boolean isSorted(int[] array) {
- boolean sorted = true;
- int i;
- for(i = 0; i < array.length - 1; i++) {
- if(array[i + 1] < array[i]) {
- sorted = false;
- break;
- }
- }
- return sorted;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement