Yet-Another-Series / Yet_Another_Algorithms_Repository

Beginner friendly repo for easily contributing algorithms' implementations
MIT License
34 stars 256 forks source link

Bubble Sort refactor | JAVA #416

Closed santiagojorda closed 4 years ago

santiagojorda commented 4 years ago

Hi, I would like to make a refactor on Bubble Sort java implementation. I think that the code looks like spaghetti and I want to apply clean code practices.

This is my first contribution to a open source project!

The original code look like `

String input = sc.nextLine();

// parse
String[] strArr = input.split(" ");
int[] numArr = new int[strArr.length];
for (int i = 0; i < numArr.length; i++) {
  numArr[i] = Integer.parseInt(strArr[i]);
}

// run Bubble Sort algorithm
boolean needSorting = true;
while (needSorting) {
  boolean swapPerformed = false;

  // start at 1st index, look backwards
  for (int i = 1; i < numArr.length; i++) {
    if (numArr[i] < numArr[i - 1]) {
      // swap needed

      // store previous int
      int prevNum = numArr[i - 1];

      numArr[i - 1] = numArr[i];
      numArr[i] = prevNum;

      swapPerformed = true;
    }
  }

  if (!swapPerformed) {
    needSorting = false;
  }
}

`