473,586 Members | 2,776 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

2-dimensional array bubble sort

20 New Member
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 34749
Ganon11
3,652 Recognized Expert Specialist
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 Recognized Expert Expert
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 Recognized Expert Top Contributor
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 Recognized Expert Expert
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 New Member
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 Recognized Expert Contributor
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 Recognized Expert Top Contributor
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 Recognized Expert Top Contributor
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 Recognized Expert Expert
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?...w hats 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

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

Similar topics

4
3664
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) Dim i, j, x As Integer x = roundarray.GetUpperBound(0) Dim tempname, tempnumber As String For i = 0 To x - 1 For j = i + 1 To x
8
4613
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
4423
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 "word", or "eelttr" for "letter". Build an array of all the keys, and sort it using a bubble sort. I have to write a modified version of bubble sort that...
5
3922
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 dimensional array of City #1 temps using a selection sort and display the sorted array c. Extract the temps recorded from all Cities as 3rd entry...
12
8631
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 multiple values. I need to make a bubble sort that reaches into an array called Tree which has in each storage location a class called Christmas Tree...
14
8022
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 program then should sort the names alphabetically by last name and display a list of all the students names and grades in alphabetical order. I have...
7
7129
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 this array. please help me. my scenario: assume that we have a big 2d char array for example students for 20 persons an 30 character for each...
0
7911
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8200
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8338
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8215
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5390
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3836
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2345
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1179
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.