[C++成长日记]将一组数据从大到小排列后输出,并显示原数组中的下标

[C++成长日记]将一组数据从大到小排列后输出,并显示原数组中的下标,第1张

题目:将一组数据从大到小排列后输出,要求显示每个元素及它们在原数组中的下标

一些比较有意思的点:

  1. 冒泡排序添加监测点work
  2. 冒泡排序的有序性可以体现出来,如截图中的44
  3. 本程序中冒泡排序交换的是地址(索引数组元素)而非原数组元素,这点非常重要,要保持原始数据不被改变;另外可以提高效率(交换数据少,但是在本程序中其实差不多,int 4字节指针 4字节)

by gzhu_fwm

#include 
using namespace std;

void autoassign(int*& p, const int len);
void sort(int* p, int len);

int main() {
	int len, * p = NULL;
	cout << "请输入数组长度:";
	cin >> len;
	autoassign(p, len);
	sort(p, len);
	delete[]p;
}
void autoassign(int*& p, const int len)//初始化一个数组,并随机赋值
{
	p = new int[len];
	srand((unsigned int)time(0));
	cout << "数组中元素有:";
	for (int i = 0; i < len; i++)//随机赋值并输出
	{
		p[i] = rand() % (99 - 10 + 1) + 10;
		cout << p[i] << " ";
	}
}
void sort(int* p, int len)
{	//创建索引数组与下标数组
	int* pnum = new int[len];//下标数组
	int** pcopy = new int* [len]; //索引数组
	for (int i = 0; i < len; i++)//初始化
	{
		pnum[i] = i; pcopy[i] = &p[i];
	}
	//经典冒泡排序
	for (int i = 0; i < len - 1; i++)
	{
		int work = 1;
		for (int k = 0; k < len - i - 1; k++)
		{
			if (*pcopy[k] < *pcopy[k + 1])
			{	//交换索引地址与下标
				swap(pcopy[k], pcopy[k + 1]);
				swap(pnum[k], pnum[k + 1]);
				work = 0;
			}
		}
		if (work) break;
	}//对排序后的数组进行输出
	cout << endl << "排序后:\n元素" << '\t' << "原数组中的下标";
	for (int j = 0; j < len; j++)
	{
		cout << endl << *pcopy[j] << " \t";
		cout << pnum[j] << "\t";
	}
	delete[]pnum;
	delete[]pcopy;
}

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/3002733.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-27
下一篇 2022-09-27

发表评论

登录后才能评论

评论列表(0条)

保存