简单选择排序(C++单链表实现)

具体实现过程为:

1、将整个记录序列划分为有序区和无序区,初始时有序区为空,无序区含有待排序所有记录。

2、在无序区中选取关键码最小记录,将它与无序区中的第一个记录交换,使得有序区扩展了一个记录,同时无序区减少了一个记录。

3、不断重复2,直到无序区只剩下一个记录为止。此时所有记录已经按关键码从小到大的顺序排列。

c++单链表实现如下:

#include<iostream>
using namespace std;
const int length(10);
struct Note
{
	int data;
	Note *next;
};
class Insert
{
public:
	Insert(int a[],int n);//初始化单链表
	void Swap(Note *m,Note *n);//交换节点data值
      //void Swap(int &a,int &b);//异或交换整形变量值的情况
	void InsertSortup();//升序排序
      //void InsertSortdown();降序排序
	void PrintList();//输出链表元素
private:
	Note *first,*p,*q;
};
Insert::Insert(int a[],int n)//头插法初始化单链表
{
	first=new Note;first->next=NULL;
	for(int i=0;i<n;i++)
	{   Note *s;
		s=new Note;s->data=a[i];
		s->next=first->next;first->next=s;
	}
}
void Insert::PrintList()//输出单链表序列
{
	p=first->next;
	while(p!=NULL)
	{
		cout<<p->data<<" ";
		p=p->next;
	}
	cout<<endl;
}
void Insert::Swap(Note *m,Note *n)//交换两个结点的data值
{
	int t;
	t=m->data;
	m->data=n->data;
	n->data=t;
}
/*
void Insert::Swap(int &a,int &b)//常引用传入参数,更改形参值得同时,实参也会受到影响
{
   a=a^b;
   b=a^b;
   a=a^b;//整形变量通过异或运算进行值交换
}
*/
void Insert::InsertSortup()//直接插入法升序排序,每一次排序从有序区第一个元素开始比较,而不是最后一个元素
{
	p=first->next;
	q=p->next;
	while(q!=NULL)//控制趟,判断无序区是否还有元素
	{
		first->data=q->data;//充当哨兵角色
		while(p!=q)
		{
			if(p->data<=first->data)p=p->next;//p指针后移,比较有序区下一个元素;降序排序仅if(p->data>=first->data)不一样
			else
			{
				Swap(p,q);//异或交换时Swap的调用为:Swap(p->data,q->data);
				p=p->next;//交换后p指针后移,比较有序区下一个元素
			}
		}
		q=q->next;p=first->next;//q指针后移,指向无序区第一个元素。p指针初始化,指向有序区第一个元素
	}
}

int main()
{
	int a[length];// = { 10,9,8,7,6,5,4,3,2,1 };
	int n;
L:cout << "请输入待排序序列的元素个数:";
	cin >> n;
	if (n > length) { cout << "请输入小于 " << length << "个元素" << endl; goto L; }
	system("cls");
	cout << "请输入待排序的序列:";
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	system("cls");
	Insert test(a, n);
	cout << "排序前的序列:";
	test.PrintList();
	test.InsertSortup();
	cout << "排序后的升序序列:";
	test.PrintList();
	return 0;
}

 
 
 

猜你喜欢

转载自blog.csdn.net/song_10/article/details/85008391