Bubble sort C++

博客介绍了在C++编程中使用冒泡排序对数组进行升序排序的方法。通过让用户输入数组大小和元素,运用冒泡排序技术对数组元素进行排序,并展示了排序后的数组,还给出了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Bubble Sort in C++

To sort an array in ascending order using bubble sort in C++ programming,

you have to ask to the user to enter the array size then ask to enter array elements,

now start sorting the array elements using the bubble sort technique and

display the sorted array on the screen as shown here in the following program.

 

#include <iostream>
using namespace std;

int main()
{
// declaration 
int n, i, arr[10], j, temp;

//
cout<<"Enter total number of elements :";
cin>>n;
cout<<"Enter "<<n<<" numbers :";
for(i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Sorting array using bubble sort technique...\n";

//  sorting
for(i=0; i<(n-1); i++)
{

// the next
for(j=0; j<(n-i-1); j++)
{
if(arr[j]>arr[j+1])
{

// swap 
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}

//
cout<<"Elements sorted successfully..!!\n";
cout<<"Sorted list in ascending order :\n";
for(i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
return 0;
}

 xfer from : 

https://codescracker.com/cpp/program/cpp-program-bubble-sort.htm

 

#include <iostream>
using namespace std;

main(){

//

int i,j;
int temp;
int n=5;
int a[5]={45,3,32,12,65};
//
for(i = 0; i < n ; i++)
for(j = n - 1 ; j > i ; j--)

{

//
if(a[j - 1] < a[j])

{

//

temp = a[j - 1];
a[j - 1]=a[j];
a[j]=temp;
}
}

//
for (int i=0;i<n;i++){

//
cout<<a[i]<<"   " ;
}
return 0;
}

转载于:https://www.cnblogs.com/poission/p/10886076.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值