先简单了解一下怎么建立一个c语言的工程项目:
https://www.cnblogs.com/jerrybaby/p/6130574.html
https://jingyan.baidu.com/article/925f8cb8f92a2bc0dde05606.html
一开始输入一组数据,然后将其进行从小到大的排序:
(果然是优秀,这题一看就知道不难对吧!!)
算法思想:
跟我们在玩扑克牌一样,在规定每个人都有固定数量牌数的前提下,每次给玩家分发一张牌,玩家会根据牌的大小进行排序,每次分发一张就排序一张,直到所有的牌都分发完毕,手上的牌也就排序完毕了!
算法伪代码:
INSERTION-SORT(A)
1 for j<- 2 to length(A)
2 do key<- A[j]
3 >将A[j]插入到排好序的序列A[1...j-1]中。
4 i<- j-1
5 while i>0 and A[i]>key
6 do A[i+1]<- A[i]
7 i<- i-1
8 A[i+1]<-key
(通过对这串伪代码的代入,发现其中变量j是不可测的,所以直接代入j=2,3直接进行检验,发现伪代码正确)
C语言:
funtion.cpp
void insertionsort(int *a,int n){
int i,j,k;
for(j=0;j<n;j++){
k=a[j];
i=j-1;
while(i>-1&&a[i]>k){
a[i+1]=a[i];
i--;
}
a[i+1]=k;
}
}
funtion.h
void insertionsort(int *a,int n);
main.cpp
#include<stdio.h>
#include"funtion.h"
int main(){
int a[]={5,1,9,4,6,2,0,3,8},i;
insertionsort(a,9);
for(i=0;i<9;i++){
printf("%d""\n",a[i]);
}
}
C++(对类的运用:https://jingyan.baidu.com/article/215817f7be97101eda142317.html):
insertionsort.h
#define _insertionsort_h
#include<iterator>
using namespace std;
template<typename Iterator>
void insertionsort(const Iterator &a,const Iterator &b){
typedef typename iterator_traits::value_type T;
int i,j,n=distance(a,b);
T key;
Iterator p,q,t;
for(j=1,q=p=a,p++,t=p;j<n;j++,q=p,p++,t=p){
key=*p;
i=j-1;
while((i>=0)&&(*q>key)){
*t=*q;
i--,t--,q--;
}
*t=key;
}
}
main.cpp
#include<iostream>
#include<string>
#include<vector>
#include<list>
#include<iterator>
using namespace std;
#include"insertionsort.h"
int main(){
int a[]={5,1,9,4,6,2,0,3,8,7},i;//同理,改变一下这里的参数还有下面的模板就行
string b[]={"Chognqing","Shanhai","Aomen","Tianjian","Beijing","XiangGan"};
double c[]={8.5,6.3,1.7,9.2,0.5,2.3,4.1,7.4,5.9,3.7};
insertionsort(a,a+10);
copy(a,a+10,ostream_iterator(cout," "));//表示分别复制从a到a+10的指针对应元素到count中,再用空格隔开分别输出
cout<<endl;
insertionsort(b,b+6);
copy(b,b+6,ostream_iterator(cout," "));
cout<<endl;
insertionsort(c,c+10);
copy(c,c+10,ostream_iterator(cout," "));
cout<<endl;
}
JAVA(https://jingyan.baidu.com/album/9f7e7ec09de5906f28155416.html?picindex=7):
Sort.java
package test;
public class Sort {
public static void insertionsort(int[] a) {
int i,j,n=a.length;
int key;
for(j=1;j<n;j++){
key=a[j];
i=j-1;
while(i>=0&&a[i]-key>0) {
a[i+1]=a[i];
i--;
}
a[i+1]=key;
}
}
}
Test.java
package test;
public class Test {
public static void main(String[] args) {
int[] a= {5,1,9,4,6,2,0,3,8,7};
int i;
Sort.insertionsort(a);
for(i=0;i<10;i++){
System.out.print(a[i]+" ");//输出语句
System.out.println();//使输出换行
}
}
}
冒泡排序:
(意思就是每次从数组后面开始取两个数进行比较,将小的数放到前面,直到所有数比完,第一个数就是最小的,然后再多次循环就能排好倒数序了)
int a[]={3,4,31,4,3,6,5,6,7},i,j,t;
for(i=1;i<9;i++){
for(j=8;j>=i;j--){
if(a[j]<a[j-1])
t=a[j-1];
a[j-1]=a[j];
a[j]=t;
}
}
}
for(i=0;i<9;i++){
printf("%d"" ",a[i]);
}