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.
- Sorting: Bubble Sort
- Discussions
Sorting: Bubble Sort
Sorting: Bubble Sort
+ 0 comments include
void countSwaps(int n, int a[]) { int numSwaps = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n - 1; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; numSwaps++; } } } printf("Array is sorted in %d swaps.\n", numSwaps); printf("First Element: %d\n", a[0]); printf("Last Element: %d\n", a[n - 1]); } int main() { int n; scanf("%d", &n); int a[n]; for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } countSwaps(n, a); return 0; }
+ 0 comments C++ SOLUTION
void countSwaps(vector<int> a) { int count = 0; for (int i = 0; i < a.size() - 1; i++) { for (int j = 0; j < a.size() - i - 1; j++) { if (a[j] > a[j + 1]) { swap(a[j],a[j+1]); count++; } } } cout << "Array is sorted in " << count << " swaps." << endl << "First Element: " << a[0] << endl << "Last Element: " << a[a.size()-1]; }
+ 0 comments public static void countSwaps(List<Integer> a) { int swaps = 0; for (int i = 0; i < a.size(); i++) { for (int j = 0; j < a.size() - 1; j++) { if (a.get(j) > a.get(j + 1)) { a.set(j + 1, a.set(j, a.get(j + 1))); swaps++; } } } System.out.println("Array is sorted in " + swaps + " swaps."); System.out.println("First Element: " + a.get(0)); System.out.println("Last Element: " + a.get(a.size() - 1)); }
+ 1 comment #python3 def countSwaps(a): numSwaps=0 n=len(a) for i in range(n): for j in range(0, n-1-i): if a[j] > a[j+1]: numSwaps+=1 a[j+1], a[j]=a[j], a[j+1] else: pass last_element = a[-1] first_element = a[0] print(f'Array is sorted in {numSwaps} swaps.\nFirst Element: {first_element}\nLast Element: {last_element}')
+ 0 comments Python Solution
current_num = 0 swap_num = 0 # Make a number of checks and potential changes equal to the length of the # array. for i in range(len(a)): for j in range(len(a) - 1): if a[j] > a[j + 1]: # Store the current number before it changes. current_num = a[j] # Perform the swap. a[j] = a[j + 1] a[j + 1] = current_num # Count up 1 swap. swap_num += 1 # Print out the statements. print(f"Array is sorted in {swap_num} swaps.") print(f"First Element: {a[0]}") print(f"Last Element: {a[len(a) - 1]}") return
Load more conversations
Sort 395 Discussions, By:
Please Login in order to post a comment