We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Day 20: Sorting
Day 20: Sorting
+ 5 comments All I did for my Cpp code was copy the example code in the problem and paste it into the sollution and write out the info required. Definitely not a challenge.
+ 2 comments We need to talk about the fact that often the tutorials in 30 days of code have nothing to do with the exercise. These things could be structured MUCH more efficiently.
+ 10 comments My solution in JAVA:
int totalSwaps=0; for (int i = n-1; i >0; i--) { int numberOfSwaps = 0; for (int j = 0; j <i; j++) { if(a[j]>a[j+1]){ int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; numberOfSwaps++; totalSwaps++; } } if (numberOfSwaps == 0) { break; } } System.out.println("Array is sorted in "+totalSwaps+" swaps."); System.out.println("First Element: "+a[0]); System.out.println("Last Element: "+a[n-1]);
+ 10 comments Python way
def bubble(arr): count_swap = 0 for num in range(len(arr)-1, 0, -1): for i in range(num): if arr[i] > arr[i+1]: arr[i], arr[i+1] = arr[i+1], arr[i] count_swap +=1 return count_swap print "Array is sorted in {} swaps.".format(bubble(a)) print "First Element: {}".format(a[0]) print "Last Element: {}".format(a[-1])
+ 1 comment Hi, I think the Bubble sort Algorithm specified, has a little drawback. The inner loop should not be running to complete length it should be (length-1 - outer loop index) and outer loop also should be running to length-1. i.e. pseudo - algorithm should be this:
for (int i = 0; i < n-1; i++) { int numberOfSwaps = 0; for (int j = 0; *j < n -i - 1 *; j++) { if (a[j] > a[j + 1]) { swap(a[j], a[j + 1]); numberOfSwaps++; } } if (numberOfSwaps == 0) { break; } }
Load more conversations
Sort 537 Discussions, By:
Please Login in order to post a comment