Home > Back-end >  Implementing a swap method in a bubble sort
Implementing a swap method in a bubble sort

Time:01-05

i have a program that i have written that allows the user to enter some votes into a system. In the end the number entered correlates to the person of that number. (0 = Ahmed, 1 = boo, etc)

  • 0 - Ahmed
  • 1 - Boo
  • 2 - Celine
  • 3 - Didi
  • 4 - Elaine

(current)At the end of the voting period the program will sort the votes in descending order and output them (once user has entered -1).

(future) the name of the candidate should be shown in this sorted list, e.g. ahmed - 5, celine - 4, didi -3, boo - 0, elaine - 0.

Currently i have the code writing the sorted vote numbers, but i am struggling to understand how it is working so i can implement the swap with the name array to produce the final result as listed before in future. Can anyone help with this. Below is my code

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String[] voteNameArray = {"Ahmed", "Boo", "Celine", "Didi", "Elaine"};
        int[] voteNumArray = new int[5];
        final int EXIT_CODE = -1;

        displayInitialText();
        int userInput = input.nextInt();
        while (userInput != EXIT_CODE) {
            if (userInput >= 0 && userInput <= 4) {
                voteNumArray[userInput] = voteNumArray[userInput]   1;
            } else {
                System.out.println("\n-----------------------");
                System.out.println("Invalid Vote - Please enter a number between 0-4");
                System.out.println("-----------------------\n");
            }
            System.out.print("Enter number of candidate you wish to vote for: ");
            userInput = input.nextInt();
        }
        sort(voteNumArray);
        displaySortedItems(voteNumArray);
    }
    public static void sort(int[] array){
        for (int i = 0; i < (array.length-1);i  ){
            for(int j = 0; j < (array.length - i -1);j  ){
                if(array[j] < array[j 1]){
                    swapPositionsOfElementsVote(array,j);
                }
            }
        }
    }
    public static void swapPositionsOfElementsVote(int[] array, int index){
        int tempStorageOfFirstIndexValue = array[index];
        array[index] = array[index   1];
        array[index   1] = tempStorageOfFirstIndexValue;
    }
    public static void displaySortedItems(int[] array){
        for (int i : array) {
            System.out.print(i   " ");
        }
        System.out.println();
    }
    public static void displayInitialText(){
        System.out.println("-----------------------" );
        System.out.println("     Candidate Vote    " );
        System.out.println("-----------------------" );
        System.out.println("Enter Candidate No. to vote!" );
        System.out.println("0 - Ahmed");
        System.out.println("1 - Boo");
        System.out.println("2 - Celine");
        System.out.println("3 - Didi");
        System.out.println("4 - Elaine");
        System.out.println("-----------------------" );
        System.out.print("Enter number of candidate you wish to vote for: ");
    }
}

CodePudding user response:

You would need a second swap function:

    public static void main(String[] args) {
        // ... ...
        // ... ...

        sort(voteNumArray, voteNameArray); // Pass the second array too
        displaySortedItems(voteNumArray);
     }
     public static void sort(int[] array, String[] names){
        for (int i = 0; i < (array.length-1);i  ){
            for(int j = 0; j < (array.length - i -1);j  ){
                if(array[j] < array[j 1]){
                    swapInts(array,j);
                    swapStrings(names,j); // Swap in second array too
                }
            }
        }
    }
    public static void swapInts(int[] array, int index){
        int temp = array[index];
        array[index] = array[index   1];
        array[index   1] = temp;
    }
    public static void swapStrings(String[] array, int index){ // Extra swap function
        String temp = array[index];
        array[index] = array[index   1];
        array[index   1] = temp;
    }

CodePudding user response:

Bubble sort compares adjacent values and swaps if not in desired order so after every pass you will get largest/minimum(depending on implementation) value at the end of array.

let assume your array is having below values and you are sorting in ascending order -

2,5,1,7,4

In First pass, i = 0 -

  1. It will compare 2,5 and 5 is greater than 2, so no swap.

  2. then it will compare 5,1 and 1 is smaller so it will swap and your array will become as below -

    2,1,5,7,4

  3. compare 5,7 and no swap as 7 is greater.

  4. compare 7,4 and swap as 4 is smaller and your array will become -

    2,5,1,4,7

After second pass, i = 1 -

2,1,4,5,7

After third pass, i = 2 -

1,2,4,5,7

Your array is sorted now, but still it will complete rest 2 passes but wont do any swap.

In every iteration you gets largest(considering ascending sorting) number in the end and thats the reason you are doing j < array.length - i -1, because you just need to sort remaining array.

  • Related