码迷,mamicode.com
首页 > 其他好文 > 详细

利用索引数组排序 不改变原数组值的位置

时间:2014-07-16 17:46:21      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   div   re   

 1.定义一个和要排序数组a[10]长度一样的数组, 这里定义为10,index[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},值为10个下标。

2. 用冒泡排序,索引值代替小下标即可

#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
    int a[10] = {4, 2, 1, 6, 7, 9, 0, 3, 5, 8};
    int index[10] = {0, 1, 2, 3, 4, 5, 6, 7 ,8, 9};
    for(int i = 0; i < 10 - 1; i++) {
        for(int j = 0; j < 10 - i - 1; j++) {
            if(a[index[j]] > a[index[j + 1]]) {
                int temp = index[j];
                index[j] = index[j + 1];
                index[j + 1] = temp;
            }
        }
    }
    for(int i = 0; i < 10; i++) {  //打印原数组(未排序)的值
        printf("%d ", a[i]);
    }
    printf("\n");
    for(int i = 0; i < 10; i++) { //打印排好序的值
        printf("%d ", a[index[i]]);
    }
    return 0;
}

 

 

利用索引数组排序 不改变原数组值的位置,布布扣,bubuko.com

利用索引数组排序 不改变原数组值的位置

标签:style   blog   color   for   div   re   

原文地址:http://www.cnblogs.com/wxzy/p/3847651.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!