Just1n2802

csc102 lab 2 Insertion Sort

Sep 24th, 2021
888
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * @author Justin Palmer
  3.  * 9/24/2021
  4.  * csc102
  5.  * Computer Science 2
  6.  * Lab 2
  7.  */
  8.  
  9.  
  10. import java.util.Scanner;
  11. import java.util.ArrayList;
  12. public class Main {
  13.     public static void main(String[] args) {
  14.         //Creating Scanner and arraylist for later use
  15.         ArrayList<Integer> al = new ArrayList<Integer>();
  16.         Scanner sc = new Scanner(System.in);
  17.  
  18.         //Getting a first number to populate the arraylist with
  19.         System.out.println("Enter a number to add to the list");
  20.         System.out.printf(">  ");
  21.         int r = sc.nextInt();
  22.         al.add(r);
  23.        
  24.         //Getting a second/last number to populate with before looping to make it easier
  25.         System.out.println("Enter a number to add to the list");
  26.         System.out.printf(">  ");
  27.         r = sc.nextInt();
  28.         if (r<al.get(0)) {
  29.             al.add(al.get(0));
  30.             al.set(0, r);
  31.         } else {
  32.             al.add(r);
  33.         }
  34.        
  35.         //creating a way to end the program on user command by exiting loop when a negative number is entered
  36.         int value = 0;
  37.         while (value==0) {
  38.             //See if the user wants to quit
  39.             System.out.println("Enter a number to add to the list or -1 to exit");
  40.             System.out.printf(">  ");
  41.             r = sc.nextInt();
  42.  
  43.             //create the escape if the user enters a negative number
  44.             if (r<0) {
  45.                 value = 1;
  46.             } else {
  47.                 //Find where the number belongs in the list
  48.                 int i = 0;
  49.                 while (i<al.size()) {
  50.                     //if the number is smallest than the first one add it as the first
  51.                     if (r<al.get(i)) {
  52.                         al.add(i, r);
  53.                         i=al.size();
  54.                     } else { // if it's not smaller than the first
  55.                         if (i==(al.size()-1)) { //then if it's not smaller than the last one it appends r
  56.                             al.add(r);
  57.                         }
  58.                         i++; // increase the index to finish the loop
  59.                     }
  60.                 }
  61.             }
  62.         }
  63.  
  64.         //Show the user their sorted list
  65.         System.out.println("Your Sorted List Is: ");
  66.         System.out.println(al);
  67.        
  68.         sc.close();
  69.     }
  70. }
RAW Paste Data