Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Does anybody have any idea that why the output is not the sorted array and how should edit the code and why the output is trash

0 views
Skip to first unread message

hamid daniali

unread,
Jul 4, 2021, 6:27:19 AM7/4/21
to
#include <iostream>
using namespace std;
void swap(int *,int *);
void sort (int [],int );
int main()
{
const int size=12;
int a[size]={1,2,96,21,17,3,9,14};
sort(a,size);
for(int i=0;i<size;i++)
cout<<a[i]<<" ";}
void sort (int a[],int size)
{
int i,j;
int *p;
p=a;
for(i=0;i<size-1;i++)
for(j=1;j<size;j++)
if (*(p+j+1)<*(p+j))
swap ((p+j+1),(p+j));}
void swap(int *pa,int *pb)
{int t;
t=*pa;
*pa=*pb;
*pb=t;
}

Benoit Izac

unread,
Jul 4, 2021, 7:00:07 AM7/4/21
to
Bonjour,

Le 04/07/2021 à 12:27, hamid daniali a écrit dans le message
<02cc39ea-e7fd-413a...@googlegroups.com> :

> #include <iostream>
> using namespace std;
> void swap(int *, int *);
> void sort(int[], int);
> int main()
> {
> const int size = 12;
> int a[size] = { 1, 2, 96, 21, 17, 3, 9, 14 };
> sort(a, size);
> for (int i = 0; i < size; i++)
> cout << a[i] << " ";
> }
>
> void sort(int a[], int size)
> {
> int i, j;
> int *p;
> p = a;
> for (i = 0; i < size - 1; i++)
> for (j = 1; j < size; j++)
> if (*(p + j + 1) < *(p + j))
> swap((p + j + 1), (p + j));
> }
>
> void swap(int *pa, int *pb)
> {
> int t;
> t = *pa;
> *pa = *pb;
> *pb = t;
> }

Il y a plusieurs problèmes :
- c'est un groupe francophone ;
- la question est dans le sujet ;
- pas d'indentation (je l'ai remis en forme) ;
- ce n'est pas du C mais du C++ ;
- il y a quatre éléments de a[] qui ne sont pas initialisés ;
- la boucle avec j est un élément en avance donc on loupe le premier
élément et on lit un élément qui n'appartient pas au tableau.

--
Benoit Izac
0 new messages