Discussion:
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
(trop ancien pour répondre)
hamid daniali
2021-07-04 10:27:18 UTC
Permalink
#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
2021-07-04 11:00:07 UTC
Permalink
Bonjour,

Le 04/07/2021 à 12:27, hamid daniali a écrit dans le message
Post by hamid daniali
#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
Loading...