3
\$\begingroup\$

How can I make this better?

public int BubbleSortNonEfficient(int[] arr) {
 int temp = 0;
 int LoopCount = 0;
 for(int write = 0; write < arr.Length; write++) {
 for(int sort = 0; sort < arr.Length - 1; sort++) {
 LoopCount++;
 if(arr[sort] > arr[sort + 1]) {
 temp = arr[sort + 1];
 arr[sort + 1] = arr[sort];
 arr[sort] = temp;
 }
 }
 }
 return LoopCount;
 }
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 28, 2016 at 17:42
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Your implementation will run in quadratic time in all cases. You can optimize here a bit:

public static int BubbleSort(int[] arr) {
 int loopCount = 0;
 for (int i = 1; i < arr.Length; ++i) {
 bool swapped = false;
 for (int j = 0; j < arr.Length - i; ++j) {
 loopCount++;
 if (arr[j] > arr[j + 1]) {
 swapped = true;
 int temp = arr [j];
 arr [j] = arr[j + 1];
 arr [j + 1] = temp;
 }
 }
 if (!swapped) {
 break;
 }
 }
 return loopCount;
}

The above alternative will run faster whenever the input array is "presorted," i.e., exhibits a lot of order.

Declaring the sort as static will allow the user to use your sort without actually instantiating the class it belongs to.

Last but not least: you can declare temp in the body of the inner loop, since it affects nothing.

answered Sep 28, 2016 at 17:59
\$\endgroup\$
2
  • \$\begingroup\$ thanks but I want to count so I can see wich ones are better \$\endgroup\$ Commented Sep 28, 2016 at 18:00
  • \$\begingroup\$ @Moder Answer edited. \$\endgroup\$ Commented Sep 28, 2016 at 18:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.