索引数组排序(c语言),通过C中的索引数组对数组进行排序

本文探讨了四种不同的算法来重新排列数组元素:冒泡排序的优化版本、N^2复杂度的解决方案、基于字符数组和索引的快速洗牌,以及一种根据预定义索引进行排序的方法。这些技巧展示了在不同场景下提高效率的不同策略。
摘要由CSDN通过智能技术生成

4 个答案:

答案 0 :(得分:5)

我的5美分:

int new_i;

for (int i = 0; i < arr_size-1; ++i)

{

while ((new_i = index_arr[i]-1) != i)

{

std::swap(struct_arr[i], struct_arr[new_i]);

std::swap(index_arr[i], index_arr[new_i]);

}

}

答案 1 :(得分:2)

O(N ^ 2)溶液:

struct S[] = {D, A, B, E, C};

int o[] = {2, 3, 5, 1, 4};

int len = 5;

for (int i=1;i<=len;++i) {

for(int j=i-1; j

if(o[j]==i) {

if (i!=j+1) {

swapSArrayItems(S, j, i-1);

swapIntArrayItems(o, j, i-1);

}

break;

}

}

}

答案 2 :(得分:0)

#include

void shuffle( char **arr, int *offs, size_t cnt);

void shuffle( char **arr, int *offs, size_t cnt)

{

unsigned idx,src,dst;

for (idx=0; idx < cnt; idx++) offs[idx] -= idx;

for (idx=0; idx < cnt; idx++) {

if (offs[idx] == 0) continue;

char *tmp;

tmp = arr[idx];

for(dst = idx; offs[dst] ; dst=src) {

src = dst+offs[dst] ;

arr[dst] = arr[src];

offs[dst] = 0;

if (offs[src] == 0 ) break;

}

arr[dst]=tmp;

}

}

int main (void)

{

unsigned idx;

char *array[5] = {"D","A","B","E","C"};

int index[5] = {1,2,4,0,3};

fprintf(stdout, "Original:\n");

for (idx=0; idx < 5; idx++) {

fprintf(stdout, "[%u]:%s\n", idx, array[idx] );

}

fprintf(stdout, "Shuffle:\n");

shuffle( array, index, 5);

fprintf(stdout, "After shuffle:\n");

for (idx=0; idx < 5; idx++) {

fprintf(stdout, "[%u]:%s\n", idx, array[idx] );

}

return 0;

}

更新:修复了连锁条件的结束(丑陋!)

答案 3 :(得分:0)

这是一个有效的版本,但请注意它确实使indices变量无效:

void sortItemsBasedOnIndices(char *items[], int indices[], size_t num)

{

// sort them

for (int i = 0; i < num; i++)

{

int newIndex = indices[i];

// take out the item at the specified index

char *newItem = items[newIndex];

// take out the item in that current position

char *oldItem = items[i];

// swap the two items

items[i] = newItem;

items[newIndex] = oldItem;

// now, tell the sorted indices the location of the old item after swap

for (int j = i; j < num; j++)

{

if (indices[j] == i)

{

indices[j] = newIndex;

break; // we only need the first one, so then we're done

}

}

}

}

int main()

{

char *items[] = { "D", "B", "E", "A", "C" };

int sortedIndices[] = { 3, 1, 4, 0, 2 }; // 0-based

int size = 5;

sortItemsBasedOnIndices(items, sortedIndices, size);

for (int i = 0; i < size; i++)

{

puts(items[i]);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值