Bubble sort

Hello. I'm trying to sort a 2D matrix of random letters from least to greatest. (A-Z) I'm making a 1D matrix to sort it, but for some reason it keeps sorting from greatest to least? Except for the first element in the matrix which is 'A' so that is correct. The rest is being sorted greatest to least.

thanks in advance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33




	int main()
	{
		char M[5][5] = { { (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65) }, { (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65) }, { (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65) }, { (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65) }, { (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65), (char)((rand() % 26) + 65) } };
		displayMatrix(M);

		int tmp;
		char S[25] = { M[0][0], M[0][1], M[0][2], M[0][3], M[0][4], M[1][0], M[1][1], M[1][2], M[1][3], M[1][4], M[2][0], M[2][1], M[2][2], M[2][3], M[2][4], M[3][0], M[3][1], M[3][2], M[3][3], M[3][4], M[4][0], M[4][1], M[4][2], M[4][3], M[4][4] };

	



	cout << endl;
	cout << endl;

	
	for (int i = 0; i < 25; i++){
		for (int j = 1; j < 24; j++){
			if (S[j] < S[i]){
				tmp = S[i];
				S[i] = S[j];
				S[j] = tmp;
			}
		}
	}

	for (int k = 0; k < 24; k++)
		cout << S[k];
Last edited on
1
2
3
4
5
6
7
8
9
10
const int MAX = 25;

for (int x = 0; x<MAX; x++)
	for (int y = 0; y<MAX - 1; y++)
		if (S[y]>S[y + 1])
		{
			int temp = S[y + 1];
			S[y + 1] = S[y];
			S[y] = temp;
		}
I'm pretty sure that bubble sort checks j-th and j+1-th member of an array not j-th and i-th

Also, you don't need that second array, all you need is pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
char Matrix[5][5] = {bleh.. bleh};
char *p = &Matrix[0][0]; //here we tell to point it to first member of an array
                                       //also char *p=Matrix[0]; would do the same, if you wonder what it does, then nvm

//now you can do this
for (int i = 0; i < 25; i++)
{
	for (int j = 0; j < 24; j++)
        {
	        if (p[j] < p[j+1])
                {
			tmp = p[j];
			p[j] = p[j+1];
			p[j+1] = tmp;
		}
	}
}
Last edited on
wow thank you so much!!!
Topic archived. No new replies allowed.