Hello :)
This is my first post on daniweb forum and I hope this site will help me improve. I'm a first year college student in computer science, and I've only recently started C++. This means that code posted by me might seem very lousy and /or unprofessional.
I have got the program to work, however, there is 1 issue I need help with.
Purpose of the program: Sorting an array of n variables in ascending order, by using cocktail sorting algorithm.
How my program works:
1. User enters the n value
2. array with n elements is generated
3. array is shown on the screen
4. array is sorted
5. sorted array is shown to the user.
The problem: When array, which is sorted already, is shown on the screen, the index of all array elements is by 1 bigger than it should be, the last array element is not shown, and 0 is shown in the place of first element.
Example:
Array1 = 1 7 5 6 3 4 2
Array2 = 0 1 2 3 4 5 6
#include <conio.h>
#include <iostream.h>
#include <stdlib.h>
void swap(int& a, int& b);
int input();
void generation();
void show();
int i,j,a[50],n;
void main(){
randomize();
input();
generation();
show();
for(i=0; i<n; i++){
if(a[i]> a[i+1]){
swap(a[i],a[i+1]);
for(j=i; j>0; j--){
if(a[j-1]>a[j]){
swap(a[j-1],a[j]);
}else{break;}
}
}
}
show();
getch();
}
int input(){
do{cout<<"Please enter the number of elements (1-30): ";
cin>>n;}while(n<1 || n>30);
return n;
}
void generation(){
for(i=0;i<n;i++){
a[i]=random(99)+1;
}
}
void show(){
for(i=0;i<n;i++){
cout<<a[i]<<"\t";
}
cout<<"\n\n\n";
}
void swap(int& a, int& b){
int pag;
pag=a;
a=b;
b=pag;
}