thorax232

Java - Missing Number

Nov 3rd, 2013
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. /* Given an array containing all numbers from 1 to N with the exception of one print the missing
  2.  * number to the standard output.
  3.  * Example input: array: 5 4 1 2 - Example output: 3
  4.  */
  5.  
  6. import java.util.*;
  7.  
  8. public class MissingNumber {
  9.     public static final java.util.Scanner input = new java.util.Scanner(System.in);
  10.  
  11.     public static void main(String[] args) {
  12.      
  13.         int len;
  14.      
  15.         System.out.print("Length of array: ");
  16.         len = input.nextInt();
  17.        
  18.         // Get array input and assign
  19.         int[] array = new int[len];
  20.         System.out.print("Enter array: ");
  21.         for(int i = 0; i < array.length; i++) {
  22.             array[i] = input.nextInt();
  23.         }
  24.        
  25.         // Sort array
  26.         array = bubble(array);
  27.        
  28.         // Compare list, print missing number when found
  29.         for(int i = 1; i < array.length; i++) {
  30.             if(i != array[i - 1]) {
  31.                 System.out.println("The missing number is: " + i);
  32.                 break;
  33.             }
  34.         }
  35.     }
  36.  
  37.     public static int[] bubble(int[] list)
  38.    {
  39.       int temp;
  40.       boolean changed = false;
  41.       do
  42.       {
  43.          changed = false; // Resets to false every time
  44.          for(int j = 0; j < list.length - 1; j++) // Minus one because if uses plus one to look at next
  45.             if(list[j] > list[j + 1]) // If next value is higher
  46.             {
  47.                temp = list[j]; // Shift value into temporary spot
  48.                list[j] = list[j + 1]; // Shift higher value into value (i)
  49.                list[j + 1] = temp; // Shift temp into higher value (swap)
  50.                changed = true;
  51.             }
  52.       } while(changed); // Stop when there's no change
  53.      
  54.       return list;
  55.    }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment