Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Given an array containing all numbers from 1 to N with the exception of one print the missing
- * number to the standard output.
- * Example input: array: 5 4 1 2 - Example output: 3
- */
- import java.util.*;
- public class MissingNumber {
- public static final java.util.Scanner input = new java.util.Scanner(System.in);
- public static void main(String[] args) {
- int len;
- System.out.print("Length of array: ");
- len = input.nextInt();
- // Get array input and assign
- int[] array = new int[len];
- System.out.print("Enter array: ");
- for(int i = 0; i < array.length; i++) {
- array[i] = input.nextInt();
- }
- // Sort array
- array = bubble(array);
- // Compare list, print missing number when found
- for(int i = 1; i < array.length; i++) {
- if(i != array[i - 1]) {
- System.out.println("The missing number is: " + i);
- break;
- }
- }
- }
- public static int[] bubble(int[] list)
- {
- int temp;
- boolean changed = false;
- do
- {
- changed = false; // Resets to false every time
- for(int j = 0; j < list.length - 1; j++) // Minus one because if uses plus one to look at next
- if(list[j] > list[j + 1]) // If next value is higher
- {
- temp = list[j]; // Shift value into temporary spot
- list[j] = list[j + 1]; // Shift higher value into value (i)
- list[j + 1] = temp; // Shift temp into higher value (swap)
- changed = true;
- }
- } while(changed); // Stop when there's no change
- return list;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment