【发布时间】:2021-01-02 04:47:04
【问题描述】:
/*Bubble sort*/
#include <iostream>
using namespace std;
//function to sort the array
int bubble_sort (int k[], int n){
int t,ct=1;
while(ct<n){
for(int i=0;i<n-ct;i++){
if(k[i]>=k[i+1]){
t=k[i];
k[i]=k[i+1];
k[i+1]=t;
}
ct++;
}
}
///loop to o/p the sorted array
for(int i=0;i<n;i++){
cout<<k[i]<<" ";
}cout<<endl;
return 0;
}
int main(){
int l;
int r[l];
cout<<"Enter the array size"<<endl;
cin>>l;
cout<<"Enter elements"<<endl;
for(int i=0;i<l;i++){
cin>>r[i];
}
bubble_sort(r,l);
return 0;
}
/*Insertion Sort*/
#include <iostream>
using namespace std;
//function to sort the array
int insertion_sort (int k[], int n){
int t,ct=1;
for(int i=1;i<n;i++){
int current=k[i];
int j=i-1;
while(k[j]>current && j>=0){
k[j+1]=k[j];
j--;
}
k[j+1]=current;
}
for(int i=0;i<n;i++){
cout<<k[i]<<" ";
}cout<<endl;
return 0;
}
int main(){
int l;
int r[l];
cout<<"Enter the array size"<<endl;
cin>>l;
cout<<"Enter elements"<<endl;
for(int i=0;i<l;i++){
cin>>r[i];
}
insertion_sort(r,l);
return 0;
}
附加的图像显示了我在运行相应代码时在终端中获得的输出(空白)。第一个算法说明了冒泡排序算法,第二个算法旨在实现插入排序技术。 非常感谢这方面的任何帮助!
在终端中输出冒泡排序代码
在终端中输出插入排序代码
【问题讨论】:
-
您的程序有未定义的行为,可能会或可能不会工作。当您编写
int r[l];时,当您稍后决定l是什么时,向导不会神奇地调整数组的大小。 -
你的程序永远不会做你想做的事,而是你告诉它做的事;)像
r[l]这样的VLA也是not part of the C++ standard,请改用std::vector。
标签: c++ visual-studio-code mingw