《算法导论》–排序算法@[TOC]算法入门(这里写自定义目录标题)
- 插入排序
//插入排序
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int num[100];
void insert_sort(int a[],int n)
{
for(int j=1;j<n;j++)//insert a[j]into the sorted sequence
{
int key=a[j];
int i=j-1;
while(i>=0&a[i]>key)
{
a[i+1]=a[i];
i--;
}
a[i+1]=key;
}
}
int main()
{
ifstream infile;int i;
infile.open("num100.txt");
for(i=0;i<100;i++)
{
infile>>num[i];
}
insert_sort(num,100);
infile.close();
ofstream outfile;
outfile.open("out.txt");
for(i=0;i<100;i++)
{
outfile<<num[i]<<" ";
}
outfile.close();
return 0;
}
我的源码(C++)
//归并排序
#include <bits/stdc++.h>
using namespace std;
int num[100];
int temp[100];
void merge_sort(int a[],int temp[],int l,int r)
{
if(l==r) return;
int mid=(l+r)/2;
merge_sort(a,temp,l,mid);
merge_sort(a,temp,mid+1,r);
for(int i=l;i<=r;i++)
temp[i]=a[i];//copy the original arry
//do the merge back to a
int i1=l,i2=mid+1;
for(int curr=l;curr<=r;curr++)
{
if(i1==mid+1) //left sublist exhaustd
a[curr]=temp[i2++];
else if(i2>r)
a[curr]=temp[i1++];
else if(temp[i1]<=temp[i2])
a[curr]=temp[i1++];
else a[curr]=temp[i2++];
}
}
int main()
{
ifstream infile;int i;
infile.open("num100.txt");
for(i=0;i<100;i++)
{
infile>>num[i];
}
merge_sort(num,temp,0,99);
infile.close();
ofstream outfile;
outfile.open("out.txt");
for(i=0;i<100;i++)
{
outfile<<num[i]<<" ";
}
outfile.close();
return 0;
}
rl/Command + Z
重做:Ctrl/Command + Y
加粗:Ctrl/Command + B
斜体:Ctrl/Command + I
标题:Ctrl/Command + Shift + H
无序列表:Ctrl/Command + Shift + U
有序列表:Ctrl/Command + Shift + O
检查列表:Ctrl/Command + Shift + C
插入代码:Ctrl/Command + Shift + K
插入链接:Ctrl/Command + Shift + L
插入图片:Ctrl/Command + Shift + G