0

This is a code I wrote for bubble sort. I gave a comment //this line due to which I'm unable to run this program. Every time the first element of the array needs to be stored in 'temp'.

#include <bits/stdc++.h>
using namespace std; 

int main()
{
    int arr[7]={7,8,5,2,4,6};
    int temp;

    for(int i=0;i<7;i++)
    {
        temp=arr[0];  //this line.

        for(int j=0;j<7-i;j++)
        {
            if(temp<arr[j])
                temp=arr[j];
            else
                swap(arr[j],arr[j-i]);
        }
    }

    for(int k=0;k<7;k++)
    {
        cout<<arr[k]<<endl;
    }

    return 0;
}
Lundin
  • 155,020
  • 33
  • 213
  • 341
era s'q
  • 314
  • 1
  • 11
  • 3
    Unrelated to your crash, but please read [Why should I not #include ?](http://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Some programmer dude May 09 '18 at 08:42
  • As for your problem, please [learn how to debug your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). Especially, if you have a crash you should use a debugger to catch it and see when and where in your code it happens, and then examine the values of all involved variables to verify that they are valid and okay. – Some programmer dude May 09 '18 at 08:44
  • 1
    `swap(arr[j],arr[j-i]);` if i=6 and j=0, it will make your program crash. – No Em May 09 '18 at 08:47
  • yeah, indexing flaw there.. Look at https://en.wikipedia.org/wiki/Bubble_sort , there is pseudocode. – Swift - Friday Pie May 09 '18 at 08:50
  • 2
    @NoEm It will lead to [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior) which can often be a cause for crashes. But it's not guaranteed to crash. – Some programmer dude May 09 '18 at 08:51
  • @Someprogrammerdude I just checked in codeblocks IDE, it crashed when called `swap` function. – No Em May 09 '18 at 09:01
  • 1
    @No Em depends on compiler and runtime, mine didn't... it's some assert state, I presume. but still, those loops are wrong for bubble sort – Swift - Friday Pie May 09 '18 at 09:07
  • 2
    @Someprogrammerdude each time I see that header include I can't get out of my head the thought that "bits" folder is named so because it's compiler's naughty bits...that never should be public – Swift - Friday Pie May 09 '18 at 09:25
  • Unrelated to the error, but do you intend to create an array of seven elements but only initialise 6 of them? The last element will just be default initialised to 0. – Sean Burton May 09 '18 at 10:09

2 Answers2

1

There were some issue with your program:

  • Array size should be 6 instead of 7
  • The for loop condition was incorrect
  • swap(arr[j],arr[j-i]) will break when j-i is less than 0(for instance i=1, j=0).

Program

#include <iostream>
#include <algorithm>
using namespace std; 

int main()
{
    int arr[6]={7,8,5,2,4,6};
    for(int i=0;i<5;i++)
    {
        for(int j=0;j<5-i;j++)
        {
            if(arr[j]>arr[j+1])
                swap(arr[j],arr[j+1]);
        }
    }
    for(int k=0;k<6;k++)
        cout<<arr[k]<<endl;
    return 0;
}

Ideone

Ishpreet
  • 3,628
  • 2
  • 15
  • 31
  • that's essentially same as my answer, but it doesn't degrade from O(n^2) to O(n) if array is sorted and uses magic numbers. – Swift - Friday Pie May 09 '18 at 13:12
  • My Bad I didn't check your answer -_- @Swift. But I tried to keep the code similar to the user's code, also mentioning its issues! You may take the accepted answer for this one :) – Ishpreet May 09 '18 at 13:36
0

You seem flipped for() loops over... what I got - not the most elegant solution, but I stick to the same tools you're using. Mostly. I could make it as template and it would work with any appropriate container. std::sort sometimes implemented like that.

#include <iostream>
#include <algorithm> 

void bubbleSort(int arr[], int n)
{
   bool swapped;
   for (int i = 0; i < n-1; i++)
   {
     swapped = false;
     for (int j = 0; j < n-i-1; j++)
     {
        if (arr[j] > arr[j+1])
        {
           std::swap(arr[j], arr[j+1]);
           swapped = true;
        }
     }

     // no elements were swapped, array already sorted.
     if (!swapped) break;
   }
}

int main()
{
    int arr[] = {7,8,5,2,4,6};

    bubbleSort(arr, std::size(arr));

    for( auto v : arr )
        std::cout << v << " ";
    std::cout << std::endl;
}

In C++11 and later <algorithm> can be replaced by <utility>, it's just for swap/size.

Swift - Friday Pie
  • 8,633
  • 1
  • 16
  • 31
  • 1
    In C++98 or later, you can also replace this whole mess with `std::sort` :) – Lundin May 09 '18 at 12:01
  • or `std::stable_sort` if a stable sorting algorithm is required (bubble sort is stable) – simon May 09 '18 at 12:04
  • @Lundin Defeats purpose of "write bubble sort" , and sot isn't necessary implemented as bubble – Swift - Friday Pie May 09 '18 at 13:11
  • My whole point here is rather that "write bubble sort" fills no purpose in the first place, outside of algorithm theory. – Lundin May 09 '18 at 13:22
  • @Lundin not true.. you never wrote for controller or for signal-processing hardware then. no vector, no std::string, no std::sort. AT best, if that's user-friendly thing like Arduino, you get simple Array and String classes. Write everything youself, optimize for particular controller, because ALU would be very exotic thing – Swift - Friday Pie May 09 '18 at 13:25
  • 1
    @Swift I have written bare metal signal-processing programs... and I have also written home-made implementations of quicksort & mergesort. Where exactly does bubble sort come in? Yeah I've used bubble sort for things like median-3 or median-5 digital filters with very little data, but I would hardly call that sorting. – Lundin May 09 '18 at 13:35
  • @Lundin A) from original question, with particular topic , answering use "std::sort" is a non-answer, b) depends what expectations of input data are and c) it is effective if it can be inlined and stay fully in stack or registers, little set , your application fits in those. d) It's one of three main questions asked when you apply for job..at least from my experience or from anyone I know (different country, different rules could be) – Swift - Friday Pie May 09 '18 at 13:40