ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

在单链表上执行气泡排序,C ++解决方案

前开发者教程 2019年2月24日

要执行气泡排序,请按照以下步骤操作:

第1步: 检查两个相邻节点上的数据是否按升序排列。如果不是,请交换2个相邻节点的数据。

第2步: 在通道1的末尾,最大的元素将在列表的末尾。在2nd pass 2nd 最大的元素将处于其位置。

第三步: 当所有元素都启动时,我们终止循环。

C ++解决方案

#include<iostream>
#include<vector>
#include<string>

using namespace std;

struct Node
{
	int data;
	Node *next;

	Node(int x)
	{
		data = x;
		next = NULL;
	}
};

void print_list(Node *head)
{
	Node *start = head;

	while(start)
	{
		cout<<start->data<<" -> ";
		start = start->next;
	}
	cout<<"\n\n";
}

void my_swap (Node *node_1, Node *node_2)
{
	int temp = node_1->data;
	node_1->data = node_2 -> data;
	node_2 -> data = temp;
}

void bubble_sort(Node *head)
{
	int swapped;

	Node *lPtr; // left pointer will always point to the start of the list
	Node *rPrt = NULL; // right pointer will always point to the end of the list
	do
	{	
		swapped = 0;
		lPtr = head;
		while(lPtr->next != rPrt)
		{
			if (lPtr->data > lPtr->next->data) 
			{
				my_swap(lPtr, lPtr->next); 
                swapped = 1; 
			}
			lPtr = lPtr->next;
		}
		//as the largest element is at the end of the list, assign that to rPtr as there is no need to
		//check already sorted list
		rPrt = lPtr;

	}while(swapped);
}

int main()
{
	Node *head = new Node(2);
	head -> next = new Node(1);
	head -> next -> next = new Node(4);
	head -> next -> next -> next = new Node(3);
	head -> next -> next -> next  -> next = new Node(6);
	head -> next -> next -> next  -> next -> next = new Node(5);

	cout<<"The original list = "<<endl;
	print_list(head);


	bubble_sort(head);

	cout<<"The Sorted list = "<<endl;
	print_list(head);

	return 0;
}

输出:

The original list =
2 -> 1 -> 4 -> 3 -> 6 -> 5 ->

The Sorted list =
1 -> 2 -> 3 -> 4 -> 5 -> 6 ->

 

该网站上可用的教程列表:

C编程20+章C ++编程80+章
100多个编码问题数据结构和算法85+章
系统设计20+章Shell脚本编写12章
4g LTE 60+章节最常见的编码问题
5G NR 50+章Linux系统编程20+章
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的



          <samp class="tHBIcXW"><sub class="nimH9ST"><input id="pE1ESxE" class="peL03hF"></input></sub></samp>
          <dl class="ZgnNG2G"></dl>


        • <dl id="ccQ98wy"></dl><em id="zA80Nk2" class="zzHUBcs"><sup id="D8eS0Lx" class="Di7NDeJ"></sup></em>
          • <caption id="cZJsB87"><strike id="YlfxcSt" class="Y3KYsAq"></strike></caption><big class="c1ZZLTU"><datalist id="JqsgOzx" class="JLbkNZ0"></datalist></big>