Cに配列(2D)があります:
80|100|70|50|120
A|C|D|F|K
私はこれにそれをソートする必要があります:
50|70|80|100|120
F|D|A|C|K
c または c++ を使用しています。私を助けてください。
ありがとう。
C++ の場合:
std::vector<int> keys;
std::vector<char> values;
std::map<int, char> kvtable;
keys.push_back(80);
values.push_back('A');
keys.push_back(100);
values.push_back('C');
keys.push_back(70);
values.push_back('D');
keys.push_back(50);
values.push_back('F');
keys.push_back(120);
values.push_back('K');
int i;
for (i = 0; i < keys.size(); i++) {
kvtable[keys[i]] = values[i];
}
std::sort(keys.begin(), keys.end());
for (i = 0; i < keys.size(); i++) {
std::cout << keys[i] << " = " << kvtable[keys[i]] << "\n";
}
次のように数値を保存する配列を作成します。
int配列[5] = {80,100,70,50,120};
2. 2 つの要素を比較する関数を作成します。
bool compare(int a,int b)
{
return a<b; //ASC
}
3. ライブラリ関数 sort() を使用します。
sort(array,array+5,compare);
4.これで、配列は ASC で正しくソートされました。
そして、次のような非常に多くの種類の並べ替えがあります。
void Swap(int &x,int &y) //not sort, just for swap two elems
{
int temp;
temp=x;
x=y;
y=temp;
}
void StraightInsertSort(int elem[],int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
temp=elem[i];
for(j=i-1;j>=0&&temp>elem[j];j--)
{
elem[j+1]=elem[j];
}
elem[j+1]=temp;
}
}
void SimpleSelectSort(int elem[],int n)
{
for(int i=0;i<n-1;i++)
{
int lowIndex=i;
for(int j=i+1;j<n;j++)
{
if(elem[j]>elem[lowIndex])
lowIndex=j;
}
Swap(elem[i],elem[lowIndex]);
}
}
void Bubblesort(int elem[],int n)
{
for(int i=n-1;i>0;i--)
{
for(int j=0;j<i;j++)
{
if(elem[j]<elem[j+1])
{
Swap(elem[j],elem[j+1]);
}
}
}
}
あなたがすべきことは、ポインターのユーティリティ 1-D 配列を配列の 1 次元に作成し、ユーティリティ配列を並べ替えるカスタム比較関数を提供することだと思います。次に、ポインター計算を実行して、配列のソートされたコピーを作成できます (必要に応じて、memcpy を使用して元の配列を上書きします)。
static int ARRAY_LEN = 5;
int[2][ARRAY_LEN] origArray;
int*[ARRAY_LEN] pointerArray;
for(int i = 0; i < ARRAY_LEN; i++){
pointerArray[i] = &origArray[0][i]; //create the pointer array
}
qsort(pointerArray, ARRAY_LEN, sizeof(int*), compar); //sort the pointer array
/*We need to define the comparison function */
int compar ( const void * elem1, const void * elem2 ){
return **(int**)elem1 - **(int**)elem2;
}
int[2][ARRAY_LEN] sortedArray;
for(int i = 0; i < ARRAY_LEN; i++){
int* curr = pointerArray[i];
int firstDimValue = *curr; // get the first dimension of the ith element of the sorted array
int secondDimValue = curr[ARRAY_LEN]; // get the 2nd dimension of the ith element of the sorted array - this works because of the way that 2D arrays are laid out in memory
sortedArray[0][i] = firstDimValue;
sortedArray[1][i] = secondDimValue;
}