Reputation: 495
I've tried implementing the bubbleSort algorithm in every way I can think of and it's still only sorting the first number. I can't understand why this is happening. Any insight would be so helpful! I tried ***Please note I have to sort an array (so can't use a vector in implementation).
bubbleSort.h
#ifndef BUBBLE_SORT_
#define BUBBLE_SORT_
#include <cstddef>
#include <iostream>
#include <array>
using std::size_t;
// void displayBag(ArrayBag &bag);
void bubbleSort(int arr[], size_t n);
#endif
bubbleSort.cpp
#include "bubbleSort.h"
#include <iostream>
#include <cstddef>
#include <array>
#include <vector>
using std::cout; using std::endl; using std::vector; using std::size_t;
/****************************************************************************/
/* Function: bubbleSort
/* Inputs: n = num of elements in arr
arr = arr to be sorted
/* Outputs: outputs sorted arr to console
/* Purpose: This function sorts arr in ascending order
/****************************************************************************/
void bubbleSort(int arr[], size_t n)
{
int i = 0;
int j = 0;
for(i; i < n; i++)
{
for(j; j < (n-1); j++)
{
if (arr[j] > arr[j+1])
{
{
int temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
}
}
main.cpp
#include "bubbleSort.h"
#include "bubbleSort.cpp"
#include <cstddef>
#include <iostream>
#include <array>
using std::cout; using std::endl;
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
size_t n = sizeof (arr) / sizeof (int);
cout << "The array has " << n << " elements." << endl;
bubbleSort(arr, n);
printf("Sorted array: \n");
for (int i=0; i < n; i++)
{
cout << arr[i] << " ";
}
return 0;
}
Upvotes: 0
Views: 284
Reputation: 145
Update your loop for two things:
Upvotes: 1
Reputation: 1250
After the first outer loop, the value of j
is already n-1
so the inner loop wont run.
After each outer loop the last i
elements are sorted so it should be for (j = 0; j < (n-i-1); j++)
Upvotes: 1