Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- public class Sorting {
- public static void main(String[] args) {
- ArrayList<Integer> array = new ArrayList<Integer>();
- array.add(9);
- array.add(8);
- array.add(7);
- array.add(6);
- array.add(5);
- array.add(4);
- array.add(3);
- array.add(2);
- array.add(1);
- array.add(17);
- array.add(18);
- ArrayList<Integer> array2 = new ArrayList<Integer>();
- array2.add(13);
- array2.add(6);
- array2.add(0);
- array2.add(6);
- array2.add(34);
- array2.add(77);
- array2.add(3);
- array2.add(2);
- array2.add(111);
- array2.add(17);
- array2.add(18);
- //Bubble Sort
- //Starts a loop at 0, goes to size - 2 to avoid trying to access an index which doesn't exist
- for(int i=0; i<= array.size()-2; i++){
- //creating k to effectively have 2 i's to cover if statement later on
- int k = i;
- //starts a nested loop. Can have i+1 and < array.size() because of -2 in parent loop
- for(int j= i+1; j< array.size(); j+=1){
- //if number in smaller index is bigger, save k as j because we gotta deal with that
- if(array.get(k)> array.get(j))
- k = j;
- }
- //gets the index of k and stores it as temporary
- int temporary = array.get(k);
- //swaps the contents of indexes k and i, but if the above if
- //statement returns false, the values are the same, so it just does nothing
- array.set(k,array.get(i));
- array.set(i, temporary);
- }
- //prints out ArrayList to make sure sorting was done correctly
- for(int i=0; i< array.size(); i++)
- System.out.print(array.get(i)+", ");
- System.out.println();
- //Selection Sort
- //Start a loop to iterate through array
- for(int i=0; i< array2.size(); i++){
- //we need a minimum, so it makes sense to start with it as the first element of the array
- int minimum = array2.get(i);
- //we need to store the index of the minimum, so its going to be temp
- int temp = i;
- //loop to search for a new minimum with every element
- for (int j = i+1; j < array2.size(); j++) {
- //if statement to find out if the proceeding element is a new minimum
- if (array2.get(j) < minimum) {
- //we found a new minimum! set it appropriately
- minimum = array2.get(j);
- //update the index of the new minimum as well
- temp = j;
- }
- }
- //once again, if the if statement above returns false, this does nothing,
- //but if it returns true, swap the contents of these indexes
- array2.set(temp, array2.get(i));
- array2.set(i, minimum);
- }
- for(int i=0; i< array2.size(); i++) {
- System.out.print( array2.get(i)+", ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement