欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

从一个无序数据元素中找到数据的最小值、次小值、次次小值对应的索引值

程序员文章站 2024-03-15 21:21:30
...
#include<iostream>
#include<time.h>
#define dim 5
using namespace std;

void swap(double a, double b,double c[dim],int index_0,int index_1)
{
	double temp;
	temp = a;
	a = b;
	b = temp;
	b = c[index_0];
	a = c[index_1];
}
void sort(double a[dim])
{
	int s1 = 0, s2 = 0, i;
	int s3 = 0;
	for (i = 0; i < dim; i++)
	{
		if (a[i] < a[s1])
		{
			s1 = i;
		}
	}
	
	for (i = 0, s2 = (s1 + 1) % dim; i < dim; i++)
	{
		if (a[i] < a[s2] && i != s1)
		{
			s2 = i;
		}
	}
	s3 = (s2 + 1) % dim;
	if (s3 == s1)
		s3 = (s2 + 1) % dim + 1;
	for (i = 0; i < dim; i++)
	{
		
		if (a[i] < a[s3] && i != s1&&i != s2)
		{
			s3 = i;
		}
	}
	cout << "first_index is " << s1 << endl;
	cout << "second_index is " << s2 << endl;
	cout << "third_index is " << s3 << endl;
}


int main()
{
	srand(time(0));
	double a[dim];
	for (int i = 0; i < dim; i++)
	{
		a[i] = rand() % (5) - 2;
		cout << " a[i] is " << a[i] << endl;
	}
	sort(a);
	system("pause");
	return 0;
}
相关标签: 排序 最小值