本文介绍了这段代码有什么错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么此代码不进行第二次迭代?
why this code doesn''t do the 2nd iteration?
#include <iostream>
using std::cout;
using std::endl;
void selectionSort( int * const, const int );
void swap( int * const, int * const );
int main(int argc, char *argv[])
{
const int arraySize = 8;
int a[ arraySize ] = { 2, 5, 12, 1, 9, 6, 3, 10 };
selectionSort( a, arraySize );
for ( int j = 1; j < arraySize; j++ )
cout << a[ j ] << " ";
cout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
void selectionSort( int * const array, const int size )
{
int smallest;
int max;
int m=0;
int i=1;
while( i < size - i && m < 2)
{
smallest = i;
max=i;
for ( int index = i + 1; index < size-i+1; index++ )
{
if ( array[ index ] < array[ smallest ] )
smallest = index;
}
for ( int x = i + 1; x < size-i+1; x++ )
{
if ( array[ x ] > array[ max ] )
max = x;
}
swap( &array[ i ], &array[ smallest ] );
swap( &array[ size-i ], &array[ max ] );
i++;
m++;
}
}
void swap( int * const element1Ptr, int * const element2Ptr )
{
int hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
}
推荐答案
void selectionSort( int * const array, const int size )
{
int smallest;
int max;
int i=0;
while( i < size - i )
{
smallest = i;
max = i;
for ( int index = i; index < size-i; index++ )
{
if ( array[ index ] < array[ smallest ] )
smallest = index;
}
swap( &array[ i ], &array[ smallest ] );
for ( int x = i; x < size-i; x++ )
{
if ( array[ x ] > array[ max ] )
max = x;
}
swap( &array[ size - ( i + 1 ) ], &array[ max ] );
i++;
}
}
这篇关于这段代码有什么错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!