473,385 Members | 1,396 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

2-dimensional array bubble sort

20
Hey, I'm working on a project that involves sorting a two-dimensional array of integers using bubble sort. I've got it semi-working, my only issue is that it seems to be 'losing' values, I'm assuming when it gets to the end of a line in the array. It also has to run several times to get the values it keeps in completely correct order.
Here's what I've got so far:
Expand|Select|Wrap|Line Numbers
  1. int SortArray (int Array[][N], int a, int b)
  2. {
  3.         int r, c;
  4.         float temp;
  5.         for (r = 0; r <= a; r ++)
  6.         {
  7.                 for (c = 0; c <= b; c ++)
  8.                 {
  9.  
  10.                                 if (Array[r][c] > Array[r + 1][c] && r + 1 <= a)
  11.                                 {
  12.                                 temp = Array[r][c];
  13.                                 Array[r][c] = Array[r + 1][c];
  14.                                 Array[r + 1][c] = temp;
  15.                                 }
  16.                                 else if (Array[r][c] > Array[r][c + 1] && c + 1 <= b)
  17.                                 {
  18.                                 temp = Array[r][c];
  19.                                 Array[r][c] = Array[r][c + 1];
  20.                                 Array[r][c + 1] = temp;
  21.                                 }
  22.                                 else if (Array[r][c] > Array[r + 1][c + 1] && r + 1 <= a && c + 1 <= b)
  23.                                 {
  24.                                 temp = Array[r][c];
  25.                                 Array[r][c] = Array[r + 1][c + 1];
  26.                                 Array[r + 1][c + 1] = temp;
  27.                                 }
  28.                 }
  29.         }
  30.         PrintArray(Array, a, b);
  31. }
  32.  
Feb 12 '07 #1
20 34678
Ganon11
3,652 Expert 2GB
I'm not sure about sorting 2D arrays, but I think you'll have to reconsider your algorithm. As far as I can tell, this algorithm looks at every 2x2 'block' in the array and moves the smallest value to the top left - but this isn't necessarily the smallest value in the entire array. You should be searching through the entire 2D array to find the smallest value, and switch it with the first element, then continue with the next.

Also, are a and b corresponding to the size of your array? If you have an array 10x10, are a and b 10 or 9? If they are 10, you will be accessing out of bounds areas of your array with array[10][10] (the 11th row, 11th column). If they are 9, you should be fine.
Feb 12 '07 #2
RedSon
5,000 Expert 4TB
Can you (in psudocode or words) describe how your algorithm is supposed to work. And please let me know what your pre and post conditions are. Like, will you accept input that is 3x4 or 8x5? How will your output be sorted?
Feb 12 '07 #3
AdrianH
1,251 Expert 1GB
You should compare your code against that in here. And you may want to reconsider using buble sort. :)

Also, when you say sort a 2D array, what do you mean? That the smallest numbers are put in the 0th row sorted by column until it is filled and then put the next smallest into the 1st row and so on? If so, there's no point, just make a 1D array, sort that and then access that like a 2D array.

Hope this helps.


Adrian
Feb 12 '07 #4
RedSon
5,000 Expert 4TB
You should compare your code against that in here. And you may want to reconsider using buble sort. :)

Also, when you say sort a 2D array, what do you mean? That the smallest numbers are put in the 0th row sorted by column until it is filled and then put the next smallest into the 1st row and so on? If so, there's no point, just make a 1D array, sort that and then access that like a 2D array.

Hope this helps.


Adrian
Hence, my question above. Can you describe what you are trying to get this algorithm to do? Also, it may be a class requirement to use bubble sort. I'm sure we can all agree that there are much better sorting algorithms.
Feb 12 '07 #5
Acolyte
20
Yeah, bubble sort is a requirement, else I'd use something more efficient.

It's a 2D array, in that is starts off as an X by Y array of random variables (The row and column variables are passed in as a and b, respectively.) I'm trying to get it to sort in increasing order.

Anyways, here's what I'm trying to get it to do:

While (cycling through the array)
If (Array[x][y] > Array(Next variable, be it next in line, or in the next row, and x + 1or y + 1 is less or equal to the length of the array)
Switch them
Feb 13 '07 #6
RRick
463 Expert 256MB
A bubble sort on a 1-D array takes 2 for loops to work. Each iteration of the inner loop takes the bottom value and filters it upward (I'm assuming a lesser to greater sort,here). Generally, this is an n ** 2 problem but there are some short cuts. For example, after the first pass, you know the last entry is correct, after the second loop, the last two entries are correct, etc.

For your 2-D case, it looks like you're going to need 4 for loops!! The inner two loops work their way through the complete matrix just once. This will force the correct value all the way to the end of the matrix. Now, you will have to do this for every cell in the array, which is what the outer two loops do. Whew!

You'll need some special logic for the last col and the last row in the matrix. You still have to check those cells but checking for cols or rows outside the matrix will only result in bugs. Also be careful who you compare the cell to. You want to compare to cells whose rows and cols are equal or one more than the current cell.
Feb 13 '07 #7
AdrianH
1,251 Expert 1GB
Hey, I'm working on a project that involves sorting a two-dimensional array of integers using bubble sort. I've got it semi-working, my only issue is that it seems to be 'losing' values, I'm assuming when it gets to the end of a line in the array. It also has to run several times to get the values it keeps in completely correct order.
Here's what I've got so far:
Expand|Select|Wrap|Line Numbers
  1. int SortArray (int Array[][N], int a, int b)
  2. {
  3.         int r, c;
  4.         float temp;
  5.         for (r = 0; r <= a; r ++)
  6.         {
  7.                 for (c = 0; c <= b; c ++)
  8.                 {
  9.  
  10.                                 if (Array[r][c] > Array[r + 1][c] && r + 1 <= a)
  11.                                 {
  12.                                 temp = Array[r][c];
  13.                                 Array[r][c] = Array[r + 1][c];
  14.                                 Array[r + 1][c] = temp;
  15.                                 }
  16.                                 else if (Array[r][c] > Array[r][c + 1] && c + 1 <= b)
  17.                                 {
  18.                                 temp = Array[r][c];
  19.                                 Array[r][c] = Array[r][c + 1];
  20.                                 Array[r][c + 1] = temp;
  21.                                 }
  22.                                 else if (Array[r][c] > Array[r + 1][c + 1] && r + 1 <= a && c + 1 <= b)
  23.                                 {
  24.                                 temp = Array[r][c];
  25.                                 Array[r][c] = Array[r + 1][c + 1];
  26.                                 Array[r + 1][c + 1] = temp;
  27.                                 }
  28.                 }
  29.         }
  30.         PrintArray(Array, a, b);
  31. }
  32.  
Yeah, bubble sort is a requirement, else I'd use something more efficient.

It's a 2D array, in that is starts off as an X by Y array of random variables (The row and column variables are passed in as a and b, respectively.) I'm trying to get it to sort in increasing order.

Anyways, here's what I'm trying to get it to do:

While (cycling through the array)
If (Array[x][y] > Array(Next variable, be it next in line, or in the next row, and x + 1or y + 1 is less or equal to the length of the array)
Switch them
So an array transform like this:
Expand|Select|Wrap|Line Numbers
  1. 8 4 3    1 2 3
  2. 7 6 5 -> 2 3 7
  3. 1 2 3    5 6 8
  4.  
An this:
Expand|Select|Wrap|Line Numbers
  1. 1 2 3    1 1 3
  2. 1 1 3 -> 1 2 3
  3. 7 8 9    7 8 9
  4.  
Interesting. I think I see why the use of Bubble sort. I think it is to make it faster and easier. Basic algorithm would be: Move the smallest number in each row to the left, then move the smallest number in each column to the top. Now do this to its sub-matrix who's top left is one column to the right and one column down from the original matrix. This is a recursive algorithm and it would be easiest to code it as one.

The sort time would be O(sum(n**2, where n=m to 0)) which is O(n**3) for large n. This could be better to implement it as a different sort and then fill the array from the top left outward which would be O(n log(n)) for sorting and O(n**2) for filling which would end up O(n**3 + (1 + log(n))) which would be O(n**3) for large n. However, for small n (if I have done the math right) using the bubble sort algorithm I suggested is faster, since n**2 is the over powering factor in the first and n**3 is the over powering factor in the second.

This was very interesting. Hope this helps you,


Adrian
Feb 13 '07 #8
AdrianH
1,251 Expert 1GB
So an array transform like this:
Expand|Select|Wrap|Line Numbers
  1. 8 4 3    1 2 3
  2. 7 6 5 -> 2 3 7
  3. 1 2 3    5 6 8
  4.  
An this:
Expand|Select|Wrap|Line Numbers
  1. 1 2 3    1 1 3
  2. 1 1 3 -> 1 2 3
  3. 7 8 9    7 8 9
  4.  
Interesting. I think I see why the use of Bubble sort. I think it is to make it faster and easier. Basic algorithm would be: Move the smallest number in each row to the left, then move the smallest number in each column to the top. Now do this to its sub-matrix who's top left is one column to the right and one column down from the original matrix. This is a recursive algorithm and it would be easiest to code it as one.

The sort time would be O(sum(n**2, where n=m to 0)) which is O(n**3) for large n. This could be better to implement it as a different sort and then fill the array from the top left outward which would be O(n log(n)) for sorting and O(n**2) for filling which would end up O(n**3 + (1 + log(n))) which would be O(n**3) for large n. However, for small n (if I have done the math right) using the bubble sort algorithm I suggested is faster, since n**2 is the over powering factor in the first and n**3 is the over powering factor in the second.

This was very interesting. Hope this helps you,


Adrian
Er, I was sort of right with the Big-O analysis. Sort time of 2D matrix sort using the algorithm I suggested would be O(sum(2*(m**2 - m), where m=2 to n)) which doesn't change the rest of my analysis.

Oh, an n represents the dimention of the array assuming that it is square. If rectangular, the Big-O results would be more complex but I'm pretty sure it would still work out better.

Adrian
Feb 13 '07 #9
RedSon
5,000 Expert 4TB
So an array transform like this:
Expand|Select|Wrap|Line Numbers
  1. 8 4 3    1 2 3
  2. 7 6 5 -> 2 3 7
  3. 1 2 3    5 6 8
  4.  
An this:
Expand|Select|Wrap|Line Numbers
  1. 1 2 3    1 1 3
  2. 1 1 3 -> 1 2 3
  3. 7 8 9    7 8 9
  4.  
Interesting. I think I see why the use of Bubble sort. I think it is to make it faster and easier. Basic algorithm would be: Move the smallest number in each row to the left, then move the smallest number in each column to the top. Now do this to its sub-matrix who's top left is one column to the right and one column down from the original matrix. This is a recursive algorithm and it would be easiest to code it as one.

The sort time would be O(sum(n**2, where n=m to 0)) which is O(n**3) for large n. This could be better to implement it as a different sort and then fill the array from the top left outward which would be O(n log(n)) for sorting and O(n**2) for filling which would end up O(n**3 + (1 + log(n))) which would be O(n**3) for large n. However, for small n (if I have done the math right) using the bubble sort algorithm I suggested is faster, since n**2 is the over powering factor in the first and n**3 is the over powering factor in the second.

This was very interesting. Hope this helps you,


Adrian
Given Adrian's analysis, it appears the recursive nature of this problem would lend it self to a divide-and-conquer algorithm. If you must use bubble sort, you must, but I think a more intuitive solution would be a merge sort. At least in my mind I can clearly see the logic path to get merge sort to work, whereas using for loops and bubble sorts would be a bit more...arcane?, convoluted?...whats the word I'm looking for here? Somebody help me out! Anyway, it would still be an interesting exercise to solve it with merge sort, and doing so would set you up nicely for later projects in your course where bubble sort is going to be worthless.
Feb 13 '07 #10
AdrianH
1,251 Expert 1GB
Given Adrian's analysis, it appears the recursive nature of this problem would lend it self to a divide-and-conquer algorithm. If you must use bubble sort, you must, but I think a more intuitive solution would be a merge sort. At least in my mind I can clearly see the logic path to get merge sort to work, whereas using for loops and bubble sorts would be a bit more...arcane?, convoluted?...whats the word I'm looking for here? Somebody help me out! Anyway, it would still be an interesting exercise to solve it with merge sort, and doing so would set you up nicely for later projects in your course where bubble sort is going to be worthless.
Actually RedSon, given my analysis, it clearly shows that Bubble Sort is not necessarily a worthless algorithm, and in fact for small n on a 2D array, it is faster and takes up less memory as it can be done in the provided memory.

When doing sorting, or anything for that matter, you should use the best tools available for the job.


Adrian
Feb 13 '07 #11
RedSon
5,000 Expert 4TB
Actually RedSon, given my analysis, it clearly shows that Bubble Sort is not necessarily a worthless algorithm, and in fact for small n on a 2D array, it is faster and takes up less memory as it can be done in the provided memory.

When doing sorting, or anything for that matter, you should use the best tools available for the job.


Adrian

You misunderstand me, for this particular application it is not worthless as you have demonstrated, but I am speaking to later topics in the course that this person is taking. They will soon find out that bubble sort it usually the worst algorithm for the job.
Feb 13 '07 #12
AdrianH
1,251 Expert 1GB
You misunderstand me, for this particular application it is not worthless as you have demonstrated, but I am speaking to later topics in the course that this person is taking. They will soon find out that bubble sort it usually the worst algorithm for the job.
Oh, ok. But it is sometimes a good idea to look at 'worthless' algorithms because they sometimes can have their uses. :)


Adrian
Feb 13 '07 #13
hi can anyone help me about my proj??
i'm 4th year h.s student...
my instructor hav me a special proj. for my failing grades...
here is my proj.
::Array of names at least 5 names, sorted alphabetically::
i'll for the response...
Feb 13 '07 #14
RedSon
5,000 Expert 4TB
hi can anyone help me about my proj??
i'm 4th year h.s student...
my instructor hav me a special proj. for my failing grades...
here is my proj.
::Array of names at least 5 names, sorted alphabetically::
i'll for the response...
If you have an unrelated question you need to start a new thread. Also, we are not going to do your work for you so you'd better post what you have already done to solve this problem and where you are having problems.
Feb 13 '07 #15
Ganon11
3,652 Expert 2GB
I think the main complication is that he's sorting a 2D array - with a 1D array, merge sort, bubble sort, quicksort, they're really all about as complicated (at least in my mind). Some are more efficient than others, but they're all about the same difficulty level for understanding.

With a 2D array, I'm not eve sure how this is supposed to be sorted yet...are each row and each column supposed to be sorted ascending from left to right/top to bottom? Is it supposed to be ascending as you read the values from left to right, top to bottom? The trouble will be defining what 'sorted' is for a 2D array, and then developing an algorithm based off a 1D sort technique.
Feb 13 '07 #16
AdrianH
1,251 Expert 1GB
I think the main complication is that he's sorting a 2D array - with a 1D array, merge sort, bubble sort, quicksort, they're really all about as complicated (at least in my mind). Some are more efficient than others, but they're all about the same difficulty level for understanding.

With a 2D array, I'm not eve sure how this is supposed to be sorted yet...are each row and each column supposed to be sorted ascending from left to right/top to bottom? Is it supposed to be ascending as you read the values from left to right, top to bottom? The trouble will be defining what 'sorted' is for a 2D array, and then developing an algorithm based off a 1D sort technique.
From what I gathered, a cell must contain a value less than or equal to the cells to the right of it and below it.

Anyways, here's what I'm trying to get it to do:

While (cycling through the array)
If (Array[x][y] > Array(Next variable, be it next in line, or in the next row, and x + 1or y + 1 is less or equal to the length of the array)
Switch them

Adrian
Feb 13 '07 #17
Acolyte
20
That would be correct.
Feb 13 '07 #18
RRick
463 Expert 256MB
I think the word you're looking for is slow. If bubble sorts are n**2 for 1-D arrays then they are (n**2)**2 = n**4 for 2-D arrays. The rest of you might wonder about the volumes of gab and ink about O(nlog(n)), but it comes down to one factor: speed.

You will remember the first time you run into a n**2 problem because you'll think the program hung. How could it take so long to run? The reason is because the n**2 algorithm that runs in 1 second with a 1000 entries will take almost two weeks to run with a million entries. I'm not kidding.

I had to dump a design and several days worth of work because of that misunderstanding. I started the program before the weekend and was amazed by how little was done by Monday. The next week was not a happy one, while I tried to make up for lost time.
Feb 13 '07 #19
RedSon
5,000 Expert 4TB
Actually I'm pretty sure I meant worthless. Re: Wikipedia

Due to its simplicity, bubble sort is often used to introduce the concept of an algorithm, or a sorting algorithm, to introductory computer science students. However, some researchers such as Owen Astrachan have gone to great lengths to disparage bubble sort and its continued popularity in computer science education, recommending that it no longer even be taught.

The Jargon file, which famously calls bogosort "the archetypical perversely awful algorithm", also calls bubble sort "the generic bad algorithm". Donald Knuth, in his famous The Art of Computer Programming, concluded that "the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems", some of which he discusses therein.
Feb 13 '07 #20
AdrianH
1,251 Expert 1GB
I think the word you're looking for is slow. If bubble sorts are n**2 for 1-D arrays then they are (n**2)**2 = n**4 for 2-D arrays. The rest of you might wonder about the volumes of gab and ink about O(nlog(n)), but it comes down to one factor: speed.

You will remember the first time you run into a n**2 problem because you'll think the program hung. How could it take so long to run? The reason is because the n**2 algorithm that runs in 1 second with a 1000 entries will take almost two weeks to run with a million entries. I'm not kidding.

I had to dump a design and several days worth of work because of that misunderstanding. I started the program before the weekend and was amazed by how little was done by Monday. The next week was not a happy one, while I tried to make up for lost time.
Yes, but in this case, Bubble Sort appears to be as good or better for small n where n is the length and width of the array. The sort time would be O(sum(2*(m**2) - m, where m=2 to n)).

Where as to do the same using a O(n lg n) sort algorithm, it would be O(n**2 lg (n**2)) to sort of n**2 values + O(n**2) for the copy, which is O(2(n**2) (lg n**2)).

We are spitting hairs here because I'm not getting rid of the constants but for an n of 10 elements (i.e. a small number like I was speaking of) complexity of Bubble sort becomes 190+153+120+91+66+45+28+15+6=714 where the complexity of a 1D O(n ln n) sort with copy would be 2*100*lg(100) which is approx equal to 1329.

Not much, but not bad.


Adrian

PS sorry for post 8 in this thread, there shouldn't have been a multiplication of the Big-O for O(n log n) sort and move calculation. It should have been addition.

Also, O(n log n) is actually incorrect (looked it up in my Introduction to Algorithms text aka The Great White Whale, cuz it is friggin big white and was like our nemesis at University :)). The actual Big-O is in lg (log base 2) not the regular log base 10. O(n log n) is usually cited because for large n, it really doesn't matter.
Feb 13 '07 #21

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Chris | last post by:
I have a bubble sort for a 2-dimensional array that sorts a string,number pair based on the number. The code for the sort is as follows: Private Sub SortArray(ByRef roundarray(,) As String)...
8
by: Protoman | last post by:
Why doesn't my double bubble sort algorithm sort; it just spits the numbers out, int the exact same order that I inputted them. Code: void swap(int& i,int& j) { i^=j; j^=i; i^=j;
0
by: Slowjam | last post by:
How do I correct the program below to search all the anagrams in a given file. First, for each word, build another word (its key) with all its letters sorted. For instance, build "dorw" for...
5
kuchma2000
by: kuchma2000 | last post by:
Hi. I have a C program (see code below) which I need to urgrade. All I need to do is: a. Extract the temps for the City #1 and store in a one dimensional array, display the array. b. Sort the one...
12
by: midknight5 | last post by:
Hello everyone, I am familiar with a normal bubble sort when dealing with an array of number but I am unsure as how to implement a sort when I have an array that is filled with classes which hold...
14
by: xtheendx | last post by:
I am writing a gradbook type program. It first allows the user to enter the number of students they want to enter. then allows them to enter the first name, last name, and grade of each student. The...
7
by: mahdiahmadirad | last post by:
Hi dears! I wrote a simple bubble sort algorithm. it works properly when we compare full arrays but i want to sort a 2d array according to a specific part of array. it has some problem to swapping...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.