Search code examples
javaarrayssorting

How to sort insert and prioritize most recent in an Array List?


I tried checking the array to see if the number is already listed, if the user happens to input a number twice thus number should be placed to the top being its most recent and everything else should be shifted down. in Short given the array [ 4, 5, 6, 7, 9] if the users inputs 7 it should be changed to [7, 4, 5, 6, 9].

//Array Created
int intArray[] = new int[5]; 

//Number of values in the array
int count = 0;

//Value user enters
int userInput = 0;

//Receive user inputs
Scanner in = new Scanner(System.in);

//First Prompt 
System.out.println("Enter The File You Wish To Use. Enter 0 to stop:");
userInput = in.nextInt();

//Keep asking for number if invalid
while((userInput < 0) || (userInput > 10)){
  System.out.println("Invalid number. Must be between 1 - 10\n");
  System.out.println("Enter The File You Wish To Use. Enter 0 to stop:");
  userInput = in.nextInt();
}

intArray[count] = userInput;
count++;


 while(userInput != 0){

   //Keeps Track of the numbers inputed 
  System.out.println("There is currently " + count + " On The Table.");
  for(int i = 0; i < count; i++){
    System.out.print(intArray[i] + " ");
  }

  System.out.print("\n\n");
  System.out.println("Enter The File You Wish To Use. Enter 0 to stop:");
  
  userInput = in.nextInt();
  
  //Don't Allow numbers bigger than 10 or less than 1
  while(userInput < 0 || userInput > 10){
    System.out.println("Invalid number.\n");
    System.out.println("Enter The File You Wish To Use. Enter 0 to stop:");
    userInput = in.nextInt();
  } 

  if(count == intArray.length){
    int tempPrev;
    for(int i = (intArray.length - 1); i > 0; i--){
      
      //Store the previous value
      tempPrev = intArray[i - 1];

      //Assign current index to what was in previous
      intArray[i] = tempPrev;
    }
    
    intArray[0] = userInput;
    count = intArray.length;
  } else {
    intArray[count] = userInput;
    count++;
  }
}
System.out.println("The end.");

} }


Solution

  • I will provide a solution for arrays and I will presume that if a new item is specified by the user, it will get to the head of the array and pulling everything to the right, with the oldest falling out of the array:

    int index = intArray.indexOf(input);
    if (index < 0) {
        index = intArray.length; //we default to the last item that would disappear
    for (int i = index; i > 0; i--) {
        intArray[i] = intArray[i - 1];
    }
    intArray[0] = input;