Advertisement
TheFastFish

array sort

Jan 13th, 2016
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. public class ArraySort {
  2.     //sort an integer array from smallest to largest
  3.     public static void main(String[] args) {
  4.         int[] numbers = new int[10];
  5.         fillArray(numbers);
  6.        
  7.         System.out.print("Starting numbers: ");
  8.         arrayPrint(numbers);
  9.        
  10.         sort(numbers);
  11.         System.out.print("Ending numbers: ");
  12.         arrayPrint(numbers);
  13.     }
  14.    
  15.     //fill an integer array with random numbers
  16.     public static void fillArray(int[] array) {
  17.         int i;
  18.        
  19.         for( i = 0; i < array.length; i++) {
  20.             array[i] = (int)(Math.random() * 100);
  21.         }
  22.     }
  23.    
  24.     //print the contents of an array
  25.     public static void arrayPrint(int[] array) {
  26.         int i;
  27.         for(i = 0; i < array.length; i++) {
  28.             System.out.printf("%2d, ", array[i]);
  29.         }
  30.         System.out.print("\n");
  31.     }
  32.    
  33.     /*
  34.      * sort an integer array
  35.      * depends on swapElement and isSorted
  36.      */
  37.     public static void sort(int[] array) {
  38.         int i;
  39.         while(!isSorted(array)) {
  40.             for(i = 0; i < array.length - 1; i++) {
  41.                 if(array[i + 1] < array[i])  swapElement(array, i, i + 1);
  42.             }
  43.         }
  44.     }
  45.    
  46.     //swaps the elements at the given indices
  47.     public static void swapElement(int[] array, int idxa, int idxb) {
  48.         int temp = array[idxa];
  49.         array[idxa] = array[idxb];
  50.         array[idxb] = temp;
  51.     }
  52.    
  53.     //test if array is sorted
  54.     public static boolean isSorted(int[] array) {
  55.         boolean sorted = true;
  56.         int i;
  57.         for(i = 0; i < array.length - 1; i++) {
  58.             if(array[i + 1] < array[i]) {
  59.                 sorted = false;
  60.                 break;
  61.             }
  62.         }
  63.         return sorted;
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement