How it works
Systematic comparisons globally.
Implementation
function exchangeSort(arr, stats) { const n = arr.length; for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { compare(i, j); if (arr[i] > arr[j]) { [arr[i], arr[j]] = [arr[j], arr[i]]; swap(i, j); } } checkpoint(i, n - 1); } for (let i = 0; i < n; i++) markSorted(i); }
def exchangeSort(arr, stats): for i in range((n - 1)): for j in range((i + 1), n): compare(i, j) if (arr[i] > arr[j]): arr[i], arr[j] = arr[j], arr[i] swap(i, j) checkpoint(i, (n - 1)) for i in range(n): markSorted(i)
#include <vector> #include <algorithm> void sort(std::vector<int>& arr, int n, int& comparisons, int& swaps) { for(int i=0; i<(n - 1); i++) { for(int j=(i + 1); j<n; j++) { compare(i, j); if((arr[i] > arr[j])) { std::swap(arr[i], arr[j]); swap(i, j); } } checkpoint(i, (n - 1)); } for(int i=0; i<n; i++) { markSorted(i); } }
public void Sort(int[] arr, int n, dynamic stats) { for(int i=0; i<(n - 1); i++) { for(int j=(i + 1); j<n; j++) { compare(i, j); if((arr[i] > arr[j])) { { int _t = arr[i]; arr[i] = arr[j]; arr[j] = _t; } swap(i, j); } } checkpoint(i, (n - 1)); } for(int i=0; i<n; i++) { markSorted(i); } }
#include <stdio.h> void sort(int arr[], int n, int* comparisons, int* swaps) { for(int i=0; i<(n - 1); i++) { for(int j=(i + 1); j<n; j++) { compare(i, j); if((arr[i] > arr[j])) { { int _t = arr[i]; arr[i] = arr[j]; arr[j] = _t; } swap(i, j); } } checkpoint(i, (n - 1)); } for(int i=0; i<n; i++) { markSorted(i); } }