Browse Source

made bubble in place

dagerob 3 years ago
parent
commit
426ed2a2d4
1 changed files with 9 additions and 18 deletions
  1. 9 18
      bubble_sort/Main.cpp

+ 9 - 18
bubble_sort/Main.cpp

@@ -23,27 +23,21 @@ int randomInt() {
 }
 
 template<typename T>
-T* bubbleSort(const T* in, int size, int (*key)(const T&)) {
-    bool madeSwap = false; // flag to know if we are done
-    // we need to create a modifiable copy of the array
-    T* out = new T[size];
-    for (unsigned int i = 0; i < size; i++) {
-        out[i] = in[i];
-    }
+void bubbleSort(T* in, int size, int (*key)(const T&)) {
+    bool madeSwap; // flag to know if we are done
     // make the bubble sort
     do {
         madeSwap = false;
         for (unsigned int i = 0; i < size - 1; i++) {
             // if this element is bigger that the next one swap places
-            if (key(out[i]) > key(out[i + 1])) {
+            if (key(in[i]) > key(in[i + 1])) {
                 madeSwap = true;
-                T val = out[i + 1];
-                out[i + 1] = out[i];
-                out[i] = val;
+                T val = in[i + 1];
+                in[i + 1] = in[i];
+                in[i] = val;
             }
         }
     } while (madeSwap);
-    return out;
 }
 
 void cacheTest() {
@@ -56,12 +50,11 @@ void cacheTest() {
             a[i] = randomInt() % max;
         }
         long time = -getMillis();
-        int* b = bubbleSort(a, size, intKey);
+        bubbleSort(a, size, intKey);
         time += getMillis();
         printf("%10ld ms | %7.2lf ms / entry \n", time,
             (static_cast<double>(time) / size));
         delete[] a;
-        delete[] b;
     }
 }
 
@@ -84,12 +77,11 @@ void structTest() {
             a[i].key = randomInt() % max;
         }
         long time = -getMillis();
-        A* b = bubbleSort(a, size, aKey);
+        bubbleSort(a, size, aKey);
         time += getMillis();
         printf("%10ld ms | %7.2lf ms / entry \n", time,
             (static_cast<double>(time) / size));
         delete[] a;
-        delete[] b;
     }
 }
 
@@ -107,7 +99,7 @@ void pointerTest() {
             a[i] = new int(randomInt() % max);
         }
         long time = -getMillis();
-        int** b = bubbleSort<int*>(a, size, pointerKey);
+        bubbleSort<int*>(a, size, pointerKey);
         time += getMillis();
         printf("%10ld ms | %7.2lf ms / entry \n", time,
             (static_cast<double>(time) / size));
@@ -115,7 +107,6 @@ void pointerTest() {
             delete a[i];
         }
         delete[] a;
-        delete[] b;
     }
 }