CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2022
    Location
    Urbana, Illinios
    Posts
    14

    Post In C, bubble sorting causes a garbage value error.

    So I've lately started learning data structures in C. Let's get back to my issue.

    Here is the code for my Bubble Sort Algorithm (Taken from Scaler Academy)

    Code:
    #include <conio.h>
    #include <math.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    void swap(int *p, int *q) {
      int temp = *p;
      *p = *q;
      *q = temp;
    }
    
    int main() {
      int arr[] = {2, 4, 1, 3, 5, 2, 3, 6, 4};  // see below for arr
      int len = sizeof(arr) / sizeof(int);
      for (int i = len - 1; i >= 0; i--) {
        for (int j = 0; j <= i; j++) {
          if (arr[j] < arr[j + 1]) {
            swap(&arr[j], &arr[j + 1]);
          }
        }
      }
      for (int m = 0; m < len; m++) {
        printf("%d\t", arr[m]);
      }
      return 0;
    }
    When I have my array set up like this: int arr[]=2,4,1,3,5,2,6,10;
    ex : int arr[]={2,4,1,3,5,2,6,10,13}; output : int arr[]={2,4,1,3,5,2,6,10};
    It sorts correctly, but when I increase the number of items in arr by one, it begins throwing trash values.
    Last edited by VictorN; October 14th, 2023 at 01:13 AM. Reason: Web link was removed.

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: In C, bubble sorting causes a garbage value error.

    Quote Originally Posted by Nathan D View Post
    So I've lately started learning data structures in C. Let's get back to my issue.

    ...
    It sorts correctly, but when I increase the number of items in arr by one, it begins throwing trash values.
    Define "it begins throwing trash values".

    And, BTW, I have texted your code and didn't see any "throwing"
    Victor Nijegorodov

  3. #3
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: In C, bubble sorting causes a garbage value error.

    look at the case when i = len - 1 and j=i
    Then j = len - 1

    you are accessing arr[j+1] = arr[len-1+1] = arr[len]

    which is outside the bounds of the array.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured