I want to do a half merge sort, that will start from the elements of the vector
What i want to do:
->Organize the elements from lower to highest
How will I do>
-> start from the elemts of vecotr
-> compare 1st and 2nd then if 1st > 2nd the first wil be the 2nd and the 2nd the 1st and then the same with the 3rd and 4th and so on
-> and then merge the 1st < 2nd with 3rd<4th ....
-> and then merge again if necesary
The problem is that I can`t go on past the 2nd step
My code :
#include <iostream>
using namespace std;
int main()
{
int A[100],n,i,x=2,fost;
cout<<"Introduceti numarul de elemente:";
cin>>n;
cout<<"Introduceti elementele:";
for(i=1;i<=n;i++)
cin>>A[i];
if(n<=1){cout<<"Elementele sunt deja sortate";return 0;}
while(x<(n/2)+1)
{
for(i=1;i<=(n/2)+1;i++)
{
if(A[i]<A[i+1]){fost=A[i];A[i]=A[i+1];A[i+1]=fost;}
else{fost=A[i+1];A[i+1]=A[i];A[i]=fost;}
Please use code tags when posting code. Highlight the code and press the <> button to the right of the edit window. Here is your code tagged and formatted:
#include <iostream>
usingnamespace std;
int
main()
{
int A[100], n, i, x = 2, fost;
cout << "Introduceti numarul de elemente:";
cin >> n;
cout << "Introduceti elementele:";
for (i = 1; i <= n; i++)
cin >> A[i];
if (n <= 1) {
cout << "Elementele sunt deja sortate";
return 0;
}
while (x < (n / 2) + 1) {
for (i = 1; i <= (n / 2) + 1; i++) {
if (A[i] < A[i + 1]) {
fost = A[i];
A[i] = A[i + 1];
A[i + 1] = fost;
} else {
fost = A[i + 1];
A[i + 1] = A[i];
A[i] = fost;
}
}
x += 1;
}
for (i = 1; i <= n; i++)
cout << A[i] << endl;
return 0;
}
Lines 19-27 aren't right. They basically say "if A[i] is less than A[i+1] then swap them, otherwise swap them." The result is that they are always swapped.
What you have here looks more like a bubble sort than a merge sort. Merge sort works recursively by sorting the left and right halves of the data, and then merging the halves together. So are you really trying to write a merge sort or are you doing bubble sort?