0
Problem Sorting an Array
I have a problem: my Code: Void sort(int a[],int N){ Int swap; For(int p=0; p< N; p++){ For (int j = 0; j < N; j++){ If (a[j] > a[j+1]){ Swap= a[j] ; a[j] = a[j+1]; a[j+1] = swap; } } } } Int main(){ Const int N = 10; Int a[] = {9,3,5,2,8,6,4,3,7,8}; sort(a,N); //loop for output: For(int k= 0; k < N; k++) Cout << a[k] << (k < N -1 ? ", " : "\n"); //Output is: // -85582..,2,3,3,4,5,6,7,8,8 //my 9 is missed Return 0; } Can someone help me?
3 Answers
+ 5
You have an array with size N. Indexing is starting from zero(0) in c++, so when you looping from 0 to N your maximum value of `j` is N - 1, that corresponds to the last element in array, then you trying to acces value `j + 1`, that is undefined so this is why you getting wrong results.
Try to use j < N - 1, instead of J < N. With it you will loop trough all elements, except last. It means, that your swap, that targets to next elemnt will return correct result
0
damn nice! I understand now :D! Thank you very much!
- 2
you have problem in capital letters đ”đ”đ”
copy & paste this code
#include <iostream>
using namespace std;
void sort(int a[],int N){
int Swap;
for(int p=0; p< N; p++){
for (int j = 0; j < N; j++){
if (a[j] > a[j+1]){
Swap= a[j] ;
a[j] = a[j+1];
a[j+1] = Swap;
}
}
}
}
int main(){
const int N = 10;
int a[] = {9,3,5,2,8,6,4,3,7,8};
sort(a,N);
//loop for output:
for(int k= 0; k < N; k++)
cout << a[k] << (k < N -1 ? ", " : "\n");
//Output is:
// -85582..,2,3,3,4,5,6,7,8,8
//my 9 is missed
return 0;
}