Hey guys , I've been working on this and I really need help to sort an array , please help and also please , just please don't post any codes..
I was trying to solve it and I spent about one hour but I needed to post this to get some help because I need to study other subjects and I got no time :(
it sort like a charm for the first few elements , until element 3 , I think the problem is in the else statement since if it's not > it will print swap " the last swap when the if statement was true " and then prints the element after which would be the same.
#include<iostream>
#include<cmath>
#include<iomanip>
#include<string>
#include <string.h>
usingnamespace std;
int main(){
constint size=5;
int array[size]={5,4,73,2,1};
int swap=0;
for (int i=0; i<size; i++){
for (int j=i+1; j<size; j++){
if (array[i]>array[j]){
swap=array[j];
array[j]=array[i];
array[i]=swap;
}
else {
swap=array[i];
}
}
array[i]=swap;
}
for (int a=0; a<size; a++){ //ignore this , this only shows the element's value after sorting
cout<<array[a]<<" ";
}
cin.get();
cin.get();
return 0;
}
edit: I overreacted, but `cin.get()' and `return 0' should be at the same indentation level
You've got a bad version of selection sort. It would be a lot easier if you modularize the code.
14 15 16 17 18 19 20
for (int i=0; i<size; i++){
//in the last element the loop would not execute
for (int j=i+1; j<size; j++){
//...
}
array[i]=swap; //swap has an invalid value
}
> it will print swap " the last swap when the if statement was true "
there is no such thing in the code that you posted.
First of all, the nested loop in your bubble sort starts in the wrong place, it should start from the index next to the first one, as in, j should always be the index next to i, so if i = 0, j should be 1, if i = 3, j should be 4. And why don't you just use the built in swap function?
the nested loop in your bubble sort starts in the wrong place,
How so ?
so if i = 0, j should be 1, if i = 3, j should be 4.
I've tried that , the problem is this causes it to swap the value and then print it again.
And why don't you just use the built in swap function?
there's one ? what's the form ?
..
Thanks a lot , I just wanted to do this myself , and it works " the last code I posted " I tried it on 5 elements array and 10 elements array and it still works.