In bubble sort, when first iteration of the inner for loop takes place, value of i
is 0
, so the loop will run till j
is less than n
, but when j
becomes equal to n-1
, and we do a[j+1]
for another time.
why doesn't this value go out of index of the array and the code executes properly?
for(i=0;i<n-1;i++) {
for(j=0;j<n-i;j++) { /* When i=0 & j<n why doesn't */
if(a[j] > a[j+1]) { /* a[j+1] go out of index when */
temp=a[j+1]; /* value of j is n-1 */
a[j+1]=a[j];
a[j]=temp;
}
}
}
Well this is a proper , Tested Bubble Sort function:
void bubble_sort(long a[], long n)
{
long i, j, t;
for (i = 0 ; c < ( n - 1 ); i++)
{
for (j = 0 ; j < n - i - 1; j++)
{
if (a[j] > a[j+1])
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
}
I think the problem is with you second for's, second argument. It should run till j
is less than i
, not n
.
void bubble(double *t, int db) {
int i, j;
for (i = db-1; i > 0; --i)
for (j = 0; j < i; ++j)
if (t[j+1] < t[j]) {
double temp = t[j];
t[j] = t[j+1];
t[j+1] = temp;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.